Skip to content

Instantly share code, notes, and snippets.

@kamaci
Last active April 4, 2022 13:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamaci/f3b8b22acc9728c808834470a611a77a to your computer and use it in GitHub Desktop.
Save kamaci/f3b8b22acc9728c808834470a611a77a to your computer and use it in GitHub Desktop.
class Solution {
public void solveSudoku(char[][] board) {
backtrack(board, 0, 0);
}
public boolean backtrack(char[][] board, int row, int col) {
//traverse from left top to bottom right
if (col == 9) { //checked all row elements, continue with the next one.
return backtrack(board, row + 1, 0);
}
if (row == 9) {
return true; //we reached the bottom right and found solution.
}
if (board[row][col] != '.') {//already set, check next element.
return backtrack(board, row, col + 1);
}
for (char c = '1'; c <= '9'; c++) {
if (!isValid(board, row, col, c)) {
continue;
}
board[row][col] = c;
if (backtrack(board, row, col + 1)) {
return true;
}
board[row][col] = '.';
}
return false;
}
public boolean isValid(char[][] board, int row, int col, char c) {
for (int i = 0; i < 9; i++) {
if (board[row][i] == c || board[i][col] == c
|| board[(row / 3) * 3 + i / 3][(col / 3) * 3 + i % 3] == c) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment