-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSudokoSolver.cpp
114 lines (99 loc) · 2.34 KB
/
SudokoSolver.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
105
106
107
108
109
110
111
112
113
114
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool isSafe(vector<vector<char>> &board, int row, int col, char dig)
{
// horizontal
for (int j = 0; j < 9; j++)
{
if (board[row][j] == dig)
{
return false;
}
}
// vertically
for (int i = 0; i < 9; i++)
{
if (board[i][col] == dig)
{
return false;
}
}
// grid
int srow = (row / 3) * 3;
int scol = (col / 3) * 3;
for (int i = srow; i <= srow + 2; i++)
{
for (int j = scol; j <= scol + 2; j++)
{
if (board[i][j] == dig)
{
return false;
}
}
}
return true;
}
bool helper(vector<vector<char>> &board, int row, int col)
{
if (row == 9) // base case
{
return true;
}
int nextRow = row, nextCol = col + 1;
if (nextCol == 9)
{
nextRow = row + 1;
nextCol = 0;
}
if (board[row][col] != '.') // if digit is already there
{
return helper(board, nextRow, nextCol);
}
// Place the digit
for (char dig = '1'; dig <= '9'; dig++)
{
if (isSafe(board, row, col, dig))
{
board[row][col] = dig;
if (helper(board, nextRow, nextCol))
{
return true;
}
board[row][col] = '.'; // backtracking
}
}
return false;
}
void solveSudoku(vector<vector<char>> &board)
{
helper(board, 0, 0);
}
void printBoard(const vector<vector<char>> &board)
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
cout << board[i][j] << " ";
}
cout << endl;
}
}
int main()
{
vector<vector<char>> board = {
{'5', '3', '.', '.', '7', '.', '.', '.', '.'},
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
{'.', '9', '8', '.', '.', '.', '.', '6', '.'},
{'8', '.', '.', '.', '6', '.', '.', '.', '3'},
{'4', '.', '.', '8', '.', '3', '.', '.', '1'},
{'7', '.', '.', '.', '2', '.', '.', '.', '6'},
{'.', '6', '.', '.', '.', '.', '2', '8', '.'},
{'.', '.', '.', '4', '1', '9', '.', '.', '5'},
{'.', '.', '.', '.', '8', '.', '.', '7', '9'}};
solveSudoku(board);
printBoard(board); // print the solved board
return 0;
}