Sudoku Solver
Time complexity: O(n ^ m) where n is the number of possibilities for each square (i.e., 9 in classic Sudoku) and m is the number of spaces that are blank.
public void solveSudoku(char[][] board) {
sudokuHeper(board);
}
public boolean sudokuHeper(char[][] board) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') {
for (char c = '1'; c <= '9'; c++) {
if (isValid(board, i, j, c)) {
board[i][j] = c;
if (sudokuHeper(board)) { // with the updated board, try if it is a vlid one.
return true;
} else {
board[i][j] = '.';
}
}
}
// after we try every single possible solution
// if we coudln't find it, return false
return false;
}
}
}
return true;
}
private boolean isValid(char[][] board, int m, int n, char val) {
// check rows
for (int j = 0; j < board[0].length; j++) {
if (board[m][j] == val)
return false;
}
// check cols
for (int i = 0; i < board.length; i++) {
if (board[i][n] == val)
return false;
}
// check regions
int I = m / 3;
int J = n / 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (val == board[I * 3 + i][J * 3 + j]) return false;
}
}
return true;
}