-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbruteForce.cpp
More file actions
86 lines (74 loc) · 2.24 KB
/
bruteForce.cpp
File metadata and controls
86 lines (74 loc) · 2.24 KB
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
include <stdio.h>
// This function finds an entry in grid that is still unassigned
bool findUnassignedCell(int grid[9][9], int &row, int &col);
// Checks whether it will be legal to assign num to the given row,col
bool isValidMove(int grid[9][9], int row, int col, int num);
//Attempt to solve the sudoku the naive way, using backtracking
bool bruteForceSolve(int grid[9][9])
{
int row, col;
// If there is no unassigned location, we are done
if (!findUnassignedCell(grid, row, col))
return true;
for (int num = 1; num <= 9; num++)
{
if (isValidMove(grid, row, col, num))
{
grid[row][col] = num;
//call this recursively TODO May change this for parallelization reasons
if (bruteForceSolve(grid))
return true;
//if this is not a valid move, then re-unassign it.
grid[row][col] = UNASSIGNED;
}
printGrid(grid);
}
return false; // trigger backtracking
}
bool findUnassignedCell(int grid[9][9], int &row, int &col)
{
printGrid(grid);
for (row = 0; row < 9; row++)
for (col = 0; col < 9; col++)
if (grid[row][col] == UNASSIGNED)
return true;
return false;
}
bool checkRow(int grid[9][9], int row, int num)
{
for (int col = 0; col < 9; col++)
if (grid[row][col] == num)
return true;
return false;
}
bool checkColumn(int grid[9][9], int col, int num)
{
for (int row = 0; row < 9; row++)
if (grid[row][col] == num)
return true;
return false;
}
bool checkBox(int grid[9][9], 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 isValidMove(Sudoku grid[9][9], int row, int col, int num)
{
return !checkColumn(grid, row, num) &&
!checkRow(grid, col, num) &&
!checkBox(grid, row - row%3 , col - col%3, num);
}
//Print out the grid.
void printGrid(int grid[9][9])
{
for (int row = 0; row < 9; row++)
{
for (int col = 0; col < 9; col++)
printf("%2d", grid[row][col]);
printf("\n");
}
}