- 문제
- 시도
- 가로, 세로, 3x3보드 내에서 중복되는 숫자가 없는지를 각각 검사하도록 내부 함수 구현
- 3가지를 모두 통과하는 숫자를 빈칸에 배치하도록 하고
- 0,0 부터 8,8까지를 전부 검사한 후, 리턴 보드하면 될 것이라고 예상
- 수도코드
const sudoku = function (board) {
const emptySpot = (board) => {
let spot = []
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[i].length; j++) {
if (board[i][j] === 0) {
spot.push([i, j])
}
}
}
}
const row = (board, r, n) => {
}
const column = (board, c, n) => {
}
const block = (board, r, c, n) => {
}
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[i].length; j++) {
if (board[i][j] === 0) {
for (let k = 0; k <= 9; k++) {
if (row(k) && column(k) && block(k)) {
board[i][j] = k
}
}
}
}
}
return board;
};
- 레퍼런스
const sudoku = function (board) {
function nextEmptySpot(board) {
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board.length; j++) {
if (board[i][j] === 0) return [i, j];
}
}
return [-1, -1];
}
function checkRow(board, row, value){
for(let i = 0; i < board[row].length; i++) {
if(board[row][i] === value) {
return false;
}
}
return true;
}
function checkColumn(board, column, value){
for(let i = 0; i < board.length; i++) {
if(board[i][column] === value) {
return false;
}
}
return true;
};
function checkSquare(board, row, column, value){
boxRow = Math.floor(row / 3) * 3;
boxCol = Math.floor(column / 3) * 3;
for (let r = 0; r < 3; r++){
for (let c = 0; c < 3; c++){
if (board[boxRow + r][boxCol + c] === value) {
return false;
}
}
}
return true;
};
function checkValue(board, row, column, value) {
if(checkRow(board, row, value) &&
checkColumn(board, column, value) &&
checkSquare(board, row, column, value)) {
return true;
}
return false;
};
let emptySpot = nextEmptySpot(board);
let row = emptySpot[0];
let col = emptySpot[1];
if (row === -1){
return board;
}
for(let num = 1; num <= board.length; num++){
if (checkValue(board, row, col, num)){
board[row][col] = num;
sudoku(board);
}
}
if (nextEmptySpot(board)[0] !== -1) {
board[row][col] = 0;
}
return board;
}