Skip to content

Create Sudoku_solver.js #580

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions 02. Algorithms/07. Backtracking/Sudoku Solver/Sudoku_solver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* https://leetcode.com/problems/sudoku-solver/
*
* Recursion | Backtracking.
* n won't exeed 9. So, It's ok
* Time O(n^n) | Space O(n)
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solveSudoku = function(board) {


const ROWS = board.length;
const COLS = board[0].length;

const isValid = (num, row, col) => {
// check the row.
for(let i = 0; i < 9; i++) {
if(board[row][i] === num) return false;
}

// check the col.
for(let i = 0; i < 9; i++) {
if(board[i][col] === num) return false;
}

// check the 3*3 grid.
const rowStart = Math.floor(row/3) * 3;
const colStart = Math.floor(col/3) * 3;
for(let i = rowStart; i < rowStart+3; i++) {
for(let j = colStart; j < colStart+3; j++) {
if(board[i][j] === num) return false;
}
}

// we can use the number.
return true;

}

const dfs = (row,col) => {
if(row === ROWS) return true;

const nextRow = col >= 8 ? row + 1 : row;
const nextCol = col >= 8 ? 0 : col + 1;

if(board[row][col] !== '.') {
if(dfs(nextRow, nextCol)) return true;
}
if(board[row][col] === '.') {
for(let i = 1; i < 10; i++) {
if(isValid(i.toString(), row, col)) {
board[row][col] = i.toString();
if(dfs(nextRow, nextCol)) return true;
board[row][col] = '.';
}
}
}
return false;
}

dfs(0,0)
};