forked from sureshmangs/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sudoku.cpp
104 lines (79 loc) · 2.4 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <bits/stdc++.h>
using namespace std;
#define UNASSIGNED 0
#define N 9
void printGrid(int grid[N][N]){
for(int row = 0; row < N; row++) {
for (int col = 0; col < N; col++)
cout<<grid[row][col]<<" ";
cout << endl;
}
}
// Searches the grid to find an entry that is still unassigned.
// If found, the reference parameters row, col will be set the location that is unassigned, and true is returned
// If no unassigned entries remain, false is returned
bool FindUnassignedLocation(int grid[N][N], int &row, int &col){
for(row = 0; row < N; row++)
for(col = 0; col < N; col++)
if (grid[row][col] == UNASSIGNED)
return true;
return false;
}
bool UsedInRow(int grid[N][N], int row, int num){
for(int col = 0; col < N; col++)
if (grid[row][col] == num)
return true;
return false;
}
bool UsedInCol(int grid[N][N], int col, int num){
for(int row = 0; row < N; row++)
if (grid[row][col] == num)
return true;
return false;
}
bool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol, int 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(int grid[N][N], int row, int col, int num){
// Check if 'num' is not already placed in current row, current column and current 3x3 box
return !UsedInRow(grid, row, num)
&& !UsedInCol(grid, col, num)
&& !UsedInBox(grid, row - row%3, col - col%3, num)
&& grid[row][col] == UNASSIGNED;
}
bool SolveSudoku(int grid[N][N]){
int row, col;
// If there is no unassigned location, we are done
if (FindUnassignedLocation(grid, row, col) == false)
return true;
// Consider digits 1 to 9
for (int num = 1; num <= 9; num++) {
if(isSafe(grid, row, col, num)) {
grid[row][col] = num;
if (SolveSudoku(grid))
return true;
grid[row][col] = UNASSIGNED; // failure, unmake & try again
}
}
return false; // this triggers backtracking
}
int main(){
// 0 means unassigned cells
int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 },
{ 5, 2, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 8, 7, 0, 0, 0, 0, 3, 1 },
{ 0, 0, 3, 0, 1, 0, 0, 8, 0 },
{ 9, 0, 0, 8, 6, 3, 0, 0, 5 },
{ 0, 5, 0, 0, 9, 0, 6, 0, 0 },
{ 1, 3, 0, 0, 0, 0, 2, 5, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 7, 4 },
{ 0, 0, 5, 2, 0, 6, 3, 0, 0 } };
if(SolveSudoku(grid) == true)
printGrid(grid);
else cout<<"No solution exists";
return 0;
}