-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku.cpp
69 lines (66 loc) · 1.73 KB
/
sudoku.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
bool FindUnassignedLocation(vector<vector<char>>A,int &row,int &column,int N)
{
for( row=0;row<N;row++)
{
for( column=0;column<N;column++)
{
if(A[row][column] == '.')
return true;
}
}
return false;
}
bool UsedInRow(vector<vector<char>>grid,int row,int col,int N,char num)
{
for (int col = 0; col < N; col++)
if(grid[row][col] == num)
return true;
return false;
}
bool UsedInCol(vector<vector<char>>grid,int row,int col,int N,char num)
{
for (int row = 0; row < N; row++)
if (grid[row][col] == num)
return true;
return false;
}
bool UsedInBox(vector<vector<char>>grid, int boxStartRow,int boxStartCol, char num)
{
for (int row = 0; row < 3; row++)
for (int col = 0; col < 3; col++)
if (grid[row + boxStartRow] [col + boxStartCol] == num)
return true;
return false;
}
bool isSafe(vector<vector<char>>A,int row,int column,int N,char num)
{
bool t1 = A[row][column] == '.';
bool t2 = !UsedInRow(A,row,column,N,num);
bool t3 = !UsedInCol(A,row,column,N,num) ;
bool t4 = !UsedInBox(A,row - row%3,column-column%3,num); // 3 for column and row division
return t1 && t2 && t3 && t4;
}
bool Sudoku(vector<vector<char>> &A,int N)
{
int row;
int column;
if(!FindUnassignedLocation(A,row,column,N))
return true;
for(char num='1';num <= '9';num++)
{
if(isSafe(A,row,column,N,num))
{
A[row][column] = num;
if (Sudoku(A,N))
return true;
A[row][column] = '.';
}
}
return false;
}
void Solution::solveSudoku(vector<vector<char> > &A)
{
int N = A.size();
Sudoku(A,N);
return;
}