-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsuduko_solver.cpp
53 lines (44 loc) · 1.59 KB
/
suduko_solver.cpp
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
/*Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
The '.' character indicates empty cells.*/
class Solution {
public:
bool isValid(vector<vector<char>>& board,int row,int col,char ch)
{
for(int i=0;i<9;i++)
{
if(board[i][col]==ch)
return false;
if(board[row][i]==ch)
return false;
if(board[3*(row/3)+i/3][3*(col/3)+i%3]==ch)
return false;
}
return true;
}
bool solve(vector < vector < char >> & board) {
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[0].size(); j++) {
if (board[i][j] == '.') {
for (char c = '1'; c <= '9'; c++) {
if (isValid(board, i, j, c)) {
board[i][j] = c;
if (solve(board))
return true;
else
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
void solveSudoku(vector<vector<char>>& board) {
solve(board);
}
};