Source Code For Sudoku Solver
Source Code For Sudoku Solver
h>
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
// for ease: global variables
const int empty = 0;
// what an empty cell counts as
const int N = 9;
// side length of puzzle
// function prototypes:
// prints the puzzle to the console;
void printPuzzle(unsigned int puzzle[N][N]);
// finds next available empty cell
bool findEmptyCell(unsigned int puzzle[N][N], unsigned int &row, unsigned int &col);
// checks if guess is acceptable
bool okayNumberToUse(unsigned int puzzle[N][N], unsigned int row, unsigned int col,
unsigned int num);
// the actual solving algorithm
bool SolveSudoku(unsigned int puzzle[N][N]);
int main(){
// 0 means empty cell
unsigned int puzzle[N][N] = {
{ 0, 9, 0, 0, 4, 0, 0,
{ 3, 0, 0, 7, 0, 5, 0,
{ 0, 0, 6, 0, 0, 0, 5,
{ 0, 3, 0, 0, 9, 0, 0,
{ 6, 0, 0, 4, 0, 2, 0,
{ 0, 5, 0, 0, 3, 0, 0,
{ 0, 0, 2, 0, 0, 0, 7,
{ 1, 0, 0, 9, 0, 6, 0,
{ 0, 8, 0, 0, 2, 0, 0,
8,
0,
0,
1,
0,
4,
0,
0,
6,
0
4
0
0
3
0
0
8
0
},
},
},
},
},
},
},
},
} };
printPuzzle(puzzle);
if (SolveSudoku(puzzle)){
printPuzzle(puzzle);
} // end if (SolveSudoku(puzzle))
else{
printf("No solution exists\n");
} // end else if (SolveSudoku(puzzle))
return 0;
} // end int main()
bool findEmptyCell(unsigned int puzzle[N][N], unsigned int &row, unsigned int &col){
for (row = 0; row < N; row++){
for (col = 0; col < N; col++){
if (puzzle[row][col] == empty){
return true;
} // end if (puzzle[row][col] == empty)
} // end for (col = 0; col < N; col++)
} // end for (row = 0; row < N; row++)
return false;
} // end bool findEmptyCell(unsigned int puzzle[N][N], unsigned int &row, unsigned int
&col)
bool okayNumberToUse(unsigned int puzzle[N][N], unsigned int row, unsigned int col,
unsigned int num){
// check cells row and column;
for (int idx = 0; idx < N; idx++){
if (puzzle[row][idx] == num || puzzle[idx][col] == num){
return false;
} // end if (puzzle[row][idx] == num || puzzle[idx][col] == num)
} // end for (int idx = 0; idx < N; idx++)