-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSudoku Solver
71 lines (63 loc) · 2.53 KB
/
Sudoku Solver
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
59
60
61
62
63
64
65
66
67
68
69
70
71
static bool isNumInRow(char **board, int size, char number, int row) {
for(int i = 0; i < size; i++)
if(board[row][i] == number)
return true;
return false;
}
static bool isNumInCol(char **board, int size, char number, int col) {
for(int i = 0; i < size; i++)
if(board[i][col] == number)
return true;
return false;
}
static bool isNumInSubBox(char **board, int size, char number, int row, int col) {
int subBoxRow = row - row % 3;
int subBoxCol = col - col % 3;
for(int i = subBoxRow; i < subBoxRow + 3; i++)
for(int j = subBoxCol; j < subBoxCol + 3; j++)
if(board[i][j] == number)
return true;
return false;
}
static bool canPlaceNum(char **board, int size, char number, int row, int col) {
// All 3 ways of placement (current row, current column and current sub-box).
// Should return false for this number
return !isNumInRow(board, size, number, row) &&
!isNumInCol(board, size, number, col) &&
!isNumInSubBox(board, size, number, row, col);
}
/**
* Algo: With the given state of the board, traverse it row by row.
* If the current cell is '.' (not digit) check all numbers from 1-9 and
* check whether each of them is valid by adding in that cell. We do the same for
* other cells same way. If at any point we find either row or col or sub-box
* violates the rules, then, we backtrack to previous cells and try placing
* different number.
* Repeat this process over and over again until it fills out all '.' cells in
* grid with valid numbers.
*/
bool backtrack(char **board, int size) {
for(int row = 0; row < size; row++) {
for(int col = 0; col < size; col++) {
if(board[row][col] == '.') {
// try every number from 1 to 9 in this cell
for(char try = '1'; try <= '9'; try++) {
if(canPlaceNum(board, size, try, row, col)) {
board[row][col] = try;
// recursively try other cells
if(backtrack(board, size))
return true;
else
board[row][col] = '.'; // reset the cell to try other numbers
}
}
return false;
}
}
}
return true;
}
void solveSudoku(char** board, int boardSize, int* boardColSize){
// fill the empty cells using backtrack strategy
backtrack(board, boardSize);
}