Created
March 1, 2017 06:54
-
-
Save hoanbka/e91a1cab2e6d38e3d81990d655dbe943 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by Albert Hoan on 2/28/2017. | |
*/ | |
function solveSudoku(board) { | |
if (board == null || board.length == 0) | |
return; | |
solve(board); | |
} | |
function solve(board) { | |
for (var i = 0; i < board.length; i++) { | |
for (var j = 0; j < board[0].length; j++) { | |
if (board[i][j] == '.') { | |
for (var c = '1'; c <= '9'; c++) {//trial. Try 1 through 9 | |
if (isValid(board, i, j, c)) { | |
board[i][j] = c; //Put c for this cell | |
if (solve(board)) | |
return true; //If it's the solution return true | |
else | |
board[i][j] = '.'; //Otherwise go back | |
} | |
} | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
function isValid(board, row, col, c) { | |
for (var i = 0; i < 9; i++) { | |
if (board[i][col] != '.' && board[i][col] == c) return false; //check row | |
if (board[row][i] != '.' && board[row][i] == c) return false; //check column | |
if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] != '.' && | |
board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) return false; //check 3*3 block | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment