Sudoku Solver

Leetcode 37.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Solution {
public void solveSudoku(char[][] board) {
backtricking(board);
}
private boolean backtricking(char[][] board){
//for loop: outside for loop rows, inside for loop columns
for(int i = 0; i < 9;i++){ //loop rows
for(int j = 0; j < 9;j++){ //loop columns
//Skip original numbers
if(board[i][j] != '.')
continue;

//Start looping 1-9 to see which one is appropriate here
for(char k = '1'; k <= '9';k++){
if(isValidSudoku(i,j,k,board)){
board[i][j] = k;
//find the appropriate one, return true
if(backtricking(board))
return true;
//undo previous operations
board[i][j] = '.';
}
}
//after looping 1 - 9, the appropriate one cannot be found, return false
return false;
}
}
//if there is no false return, which means that appropriate positions have been found on the board
return true;
}
//There are three dimensions to determine whether a chessboard is valid:
// No duplicates in each row
// No duplicates in each column
// No duplicates in the sub boxes of the grid
public boolean isValidSudoku(int row, int col, char val, char[][] board){
//No duplicates in each row
for(int i = 0; i < 9;i++){
if(board[row][i] == val)
return false;
}
//No duplicates in each column
for(int i = 0;i < 9;i++){
if(board[i][col] == val)
return false;
}
//No duplicates in sub boxes
int startRow = (row / 3) * 3;
int startColumn = (col / 3) * 3;
for(int i = startRow; i < startRow + 3;i++){
for(int j = startColumn; j < startColumn + 3;j++){
if(board[i][j] == val)
return false;
}
}
//if there is no false return
return true;
}
}