I am currently working on sudoku solver that utilizes backtracking in order to solve the sudoku. I am almost finished but it crashes and I have no idea why,I tried searching the problems here related to sudoku backtracking but not much light was shed, as far as I could narrow down the problem, i know it is in my solveBoard function but still not sure, I also tried searching throught different sites and got some help but not enough. any help? thanks in advance
#include <iostream>
using namespace std;
bool findBlankLocation(int board[9][9], int&, int&);
bool inColumn(int [9][9], int, int);
bool inRow(int [9][9], int, int);
bool inBox(int [9][9], int, int, int);
bool blankLocation(int[9][9], int, int, int);
void printBoard(int [9][9]);
bool solveBoard(int [9][9]);
int main()
{
int board[9][9] = {{3, 0, 6, 5, 0, 8, 4, 0, 0},
{5, 2, 0, 0, 0, 0, 0, 0, 0},
{0, 8, 7, 0, 0, 0, 0, 3, 1},
{0, 0, 3, 0, 1, 0, 0, 8, 0},
{9, 0, 0, 8, 6, 3, 0, 0, 5},
{0, 5, 0, 0, 9, 0, 6, 0, 0},
{1, 3, 0, 0, 0, 0, 2, 5, 0},
{0, 0, 0, 0, 0, 0, 0, 7, 4},
{0, 0, 5, 2, 0, 6, 3, 0, 0}};
if(solveBoard(board) == true)
printBoard(board);
else
cout << "\n\n>>>>No existe solucion...";
return 0;
}
bool findBlankLocation(int board[9][9], int &row, int &col)
{
for(int row=0; row<9;row++)
for(int col=0; col<9;col++)
if(board[row][col] == 0)
return true;
return false;
}
bool inColumn(int board[9][9], int col, int number)
{
for(int row=0; row<9; row++)
if(number == board[row][col])
return true;
return false;
}
bool inRow(int board [9][9], int row, int number)
{
for(int col=0; col<9; col++)
if(number == board[row][col])
return true;
return false;
}
bool inBox(int board[9][9], int startRow, int startColumn, int num)
{
for(int row = 0; row<3; row++)
for(int col = 0; col<3; col++)
if(board[row+startRow][col+startColumn] == num)
return true;
return false;
}
void printBoard(int board[9][9])
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
cout << " " << board[i][j];
cout << endl;
}
}
bool blankLocation(int board[9][9], int row, int col, int num)
{
return !inColumn(board, col, num) && !inRow(board, row, num)
&& !inBox( board, row-row%3, col-col%3, num);
}
bool solveBoard(int board[9][9])
{
int row, col;
if (!findBlankLocation(board, row, col))
return true;
for (int num = 1; num <= 9; num++)
{
if (blankLocation(board, row, col, num))
{
board[row][col] = num;
if (solveBoard(board))
return true;
board[row][col] = 0;
}
}
return false;
}