Skip to content

Commit 2a97f35

Browse files
committed
Add 'Sudoku Solver' solution.
1 parent 41b623e commit 2a97f35

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

Sudoku_Solver.cpp

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
Write a program to solve a Sudoku puzzle by filling the empty cells.
3+
Empty cells are indicated by the character '.'.
4+
You may assume that there will be only one unique solution.
5+
*/
6+
7+
class Solution {
8+
public:
9+
10+
bool isValid(vector<vector<char> > &board, int x, int y) {
11+
for (int i=0; i<9; i++) {
12+
if (i != x && board[i][y] == board[x][y]) return false;
13+
}
14+
for (int j=0; j<9; j++) {
15+
if (j != y && board[x][j] == board[x][y]) return false;
16+
}
17+
int sx = x / 3 * 3, sy = y / 3 * 3;
18+
for (int i=sx; i<sx+3; i++) {
19+
for (int j=sy; j<sy+3; j++) {
20+
if (i != x && j != y && board[i][j] == board[x][y]) return false;
21+
}
22+
}
23+
return true;
24+
}
25+
26+
bool solveSudokuDFS(vector<vector<char> > &board, int x, int y) {
27+
x = x + y / 9;
28+
y = y % 9;
29+
if (x == 9) return true;
30+
31+
if (board[x][y] == '.') {
32+
for (char k='1'; k<='9'; k++) {
33+
board[x][y] = k;
34+
if (isValid(board, x, y) && solveSudokuDFS(board, x, y+1)) return true;
35+
board[x][y] = '.';
36+
}
37+
return false;
38+
}
39+
return solveSudokuDFS(board, x, y+1);
40+
}
41+
42+
void solveSudoku(vector<vector<char> > &board) {
43+
solveSudokuDFS(board, 0, 0);
44+
}
45+
};

Sudoku_Solver.exe

682 KB
Binary file not shown.

Sudoku_Solver.o

199 KB
Binary file not shown.

0 commit comments

Comments
 (0)