Skip to content
GitLab
Menu
Projects
Groups
Snippets
/
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
nrossol
Sudoku Backtracking
Commits
eb8e7347
Commit
eb8e7347
authored
Aug 11, 2020
by
nrossol
Browse files
Initial Commit
parents
Changes
1
Hide whitespace changes
Inline
Side-by-side
sudokuSolver.cpp
0 → 100644
View file @
eb8e7347
#include
<iostream>
#include
<map>
#include
<set>
//Backtracking & recursive algorithm to solve sudoku puzzle if possible, to be implemented in python with a GUI later.
//Sudoku rules: The grid has 81 squares: 9 boxes of 9 squares. Each box must contain
//all numbers 1-9 in its squares, and each number can appear only once in any row,
//column, or box.
bool
solveSudoku
(
int
**
grid
){
std
::
pair
<
int
,
int
>
zeroIndex
;
//row,col of the zero to be filled.
bool
foundZero
=
findZero
(
grid
,
zeroIndex
);
if
(
foundZero
){
for
(
int
i
=
1
;
i
<
10
;
++
i
){
grid
[
zeroIndex
.
first
,
zeroIndex
.
second
]
=
i
;
if
(
checkSolution
(
grid
,
zeroIndex
.
first
,
zeroIndex
.
second
)){
solveSudoku
(
grid
);
}
}
grid
[
zeroIndex
.
first
,
zeroIndex
.
second
]
=
0
;
return
false
;
}
else
{
return
true
;
//solved
}
}
//Helper functions:
//checks the solution for a given index and returns true if valid.
bool
checkSolution
(
int
**
grid
,
const
int
&
row
,
const
int
&
col
){
for
(
int
i
=
0
;
i
<
9
;
++
i
){
if
(
grid
[
i
][
col
]
==
grid
[
row
][
col
]
&&
i
!=
row
)
{
return
false
;
}
else
if
(
grid
[
row
][
i
]
==
grid
[
row
][
col
]
&&
i
!=
col
){
return
false
;
}
}
return
true
;
}
//Finds the index of the next zero to be solved.
bool
findZero
(
int
**
grid
,
std
::
pair
<
int
,
int
>
&
zeroIndex
){
for
(
int
i
=
0
;
i
<
9
;
++
i
){
for
(
int
j
=
0
;
j
<
9
;
++
j
){
if
(
grid
[
i
][
j
]
==
0
)
{
zeroIndex
.
first
=
i
;
zeroIndex
.
second
=
j
;
return
true
;
}
}
}
return
false
;
}
//Prints the board.
void
printBoard
(){
for
(
int
i
=
0
;
i
<
9
;
++
i
){
for
(
int
j
=
0
;
j
<
9
;
++
j
){
std
::
cout
<<
grid
{
i
][
j
]
<<
" "
;}
}
std
::
cout
<<
std
::
endl
;
}
}
int
main
()
{
//Easy Grid:
int
grid
[
9
][
9
]
=
{
{
1
,
2
,
3
,
0
,
5
,
6
,
7
,
8
,
9
},
{
0
,
5
,
6
,
7
,
8
,
9
,
1
,
2
,
3
},
{
7
,
8
,
0
,
1
,
2
,
3
,
4
,
5
,
6
},
{
2
,
1
,
4
,
3
,
6
,
5
,
0
,
9
,
7
},
{
3
,
0
,
5
,
8
,
9
,
7
,
2
,
1
,
4
},
{
8
,
9
,
7
,
2
,
1
,
4
,
3
,
6
,
0
},
{
5
,
3
,
1
,
6
,
4
,
2
,
9
,
0
,
8
},
{
6
,
4
,
2
,
9
,
0
,
8
,
5
,
3
,
1
},
{
9
,
7
,
8
,
0
,
3
,
1
,
6
,
4
,
2
}
};
//Medium Grid:
//Hard Grid:
if
(
solveSudoku
(
grid
)
==
true
)
{
std
::
cout
<<
"Solved!"
<<
std
::
endl
;}
else
{
std
::
cout
<<
"Unsolvable :("
<<
std
::
endl
;}
printBoard
();
return
0
;
}
\ No newline at end of file
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment