-
Notifications
You must be signed in to change notification settings - Fork 0
/
SudokuSolver.cpp
80 lines (77 loc) · 2.31 KB
/
SudokuSolver.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
#include "Sudokusolver.h"
#include <iostream>
void Sudokusolver::Print(int board[9][9]){
for (int rows = 0; rows < (sizeof(board[0])/sizeof(*board[0])); rows++)
{
for (int cols = 0; cols < (sizeof(board[0])/sizeof(*board[0])); cols++)
{
std::cout << board[rows][cols] << " ";
if((cols + 1) % 3 == 0 && cols != 8){
std::cout << "|";
}
}
if((rows + 1) % 3 == 0 && rows != 8){
std::cout << "\n-------------------";
}
std::cout << "\n";
}
std::cout << "\n";
}
bool Sudokusolver::checkLine(int board[9][9], int n, int row, int col){
for (int number = 0; number < (sizeof(board[0])/sizeof(*board[0])); number++)
{
if (board[row][number] == n || board[number][col] == n)
{
return false;
}
}
return true;
}
bool Sudokusolver::checkBox(int board[9][9], int n, int row, int col){
int topRow, topCol;
topRow = row / 3 * 3;
topCol = col / 3 * 3;
for (int i = topRow; i < topRow + 3; i++)
{
for (int j = topCol; j < topCol + 3; j++)
{
if (board[i][j] == n)
{
return false;
}
}
}
return true;
}
bool Sudokusolver::isValid(int board[9][9], int n, int row, int col){
return checkLine(board, n, row, col) && checkBox(board, n, row, col);
}
bool Sudokusolver::solveBoard(int board[9][9]){
for (int rows = 0; rows < (sizeof(board[0])/sizeof(*board[0])); rows++)
{
for (int cols = 0; cols < (sizeof(board[0])/sizeof(*board[0])); cols++)
{
if (board[rows][cols] == 0)
{
for (int nToTry = 0; nToTry <= (sizeof(board[0])/sizeof(*board[0])); nToTry++)
{
if (isValid(board,nToTry, rows, cols))
{
board[rows][cols] = nToTry;
if (solveBoard(board))
{
return true;
}
else
{
board[rows][cols] = 0;
}
}
}
return false;
}
}
}
Print(board);
return true;
}