-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolver.cpp
73 lines (62 loc) · 1.41 KB
/
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "constants.h"
#include "GridClass.h"
bool findUnfilledCell(GridClass& grid, int& row, int& col);
bool noConflict(const GridClass& grid,
const int rowID, const int colID, const int num);
bool solveSudoku(GridClass& grid)
{
int row, col;
if (!findUnfilledCell(grid, row, col))
{
return true;
}
for (int num = 1; num <= 9; ++num)
{
if (noConflict(grid, row, col, num))
{
grid.writeCell(row, col, num);
if (solveSudoku(grid))
{
return true;
}
grid.writeCell(row, col, UNFILLED);
}
}
return false;
}
bool findUnfilledCell(GridClass& grid, int& row, int& col)
{
for (row = 1; row <= 9; ++row)
{
for (col = 1; col <= 9; ++col)
{
if (grid.readCell(row, col) == UNFILLED)
{
return true;
}
}
}
return false;
}
bool noConflict(const GridClass& grid,
const int rowID, const int colID, const int num)
{
int row[9], col[9], box[9];
bool usedInRow, usedInCol, usedInBox;
grid.getRow(rowID, row);
grid.getCol(colID, col);
grid.getBox(grid.getBoxNum(rowID, colID), box);
usedInRow = false;
usedInCol = false;
usedInBox = false;
for (int i = 0; i < 9; ++i)
{
if (row[i] == num)
usedInRow = true;
if (col[i] == num)
usedInCol = true;
if (box[i] == num)
usedInBox = true;
}
return (!usedInRow && !usedInCol && !usedInBox);
}