Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Need Help With My code

killerelitekillerelite MPASSWORDYMember Posts: 1

include

using namespace std;
int sudoku[9][9] = { { 0, 0, 0, 0, 0, 0, 0, 9, 0 },
{ 1, 9, 0, 4, 7, 0, 6, 0, 8 },
{ 0, 5, 2, 8, 1, 9, 4, 0, 7 },
{ 2, 0, 0, 0, 4, 8, 0, 0, 0 },
{ 0, 0, 9, 0, 0, 0, 5, 0, 0 },
{ 0, 0, 0, 7, 5, 0, 0, 0, 9 },
{ 9, 0, 7, 3, 6, 4, 1, 8, 0 },
{ 5, 0, 6, 0, 8, 1, 0, 7, 4 },
{ 0, 8, 0, 0, 0, 0, 0, 0, 0 } };
int checker[81][2];
int check = 0;
void solvesudoku(int, int);
bool checkrow(int row, int num)
{
for (int column = 0; column < 9; column++)
if (sudoku[row][column] == num)
return false;
return true;
}
bool checkcolumn(int column, int num)
{
for (int row = 0; row < 9; row++)
if (sudoku[row][column] == num)
return false;
return true;
}
bool checkgrid(int row, int column, int num)
{
row = (row / 3) * 3;
column = (column / 3) * 3;
int r, c;
for (r = 0; r < 3; r++)
for (c = 0; c < 3; c++)
if (sudoku[row + r][column + c] == num)
return false;
return true;
}
void navigate(int &row, int &column)
{
if (column < 8)
column++;
else
{
column = 0;
row++;
}
}
void display()
{
int row, column;
cout << "Soloution=" << endl;
for (row = 0; row<9; row++)
{
for (column = 0; column < 9; column++)
{
cout << sudoku[row][column];
if ((column + 1) % 3 == 0)
cout << " ";
}
cout << endl;
if ((row + 1) % 3 == 0)
cout << endl;
}
system("pause");
}
void navigatebackward()
{
check--;
int row = checker[check][0];
int column = checker[check][1];
for (int safe = sudoku[row][column]+1; safe <= 9; safe++)
{
if (checkrow(row, safe) == true && checkcolumn(column, safe) == true && checkgrid(row, column, safe) == true)
{
sudoku[row][column] = safe;
check++;
break;
}
else
{
sudoku[row][column] = 0;
}
}
if (sudoku[row][column] == 0)
navigatebackward();
navigate(row,column);

}
void solvesudoku(int row = 0, int column = 0)
{
while (row < 8)
{
if (sudoku[row][column] != 0)
navigate(row, column);
else
{
checker[check][0] = row;
checker[check][1] = column;
for (int safe = 1; safe <= 9; safe++)
{
if (checkrow(row, safe) == true && checkcolumn(column, safe) == true && checkgrid(row, column, safe) == true)
{
sudoku[row][column] = safe;
check++;
display();
break;
}
}
if (sudoku[row][column] == 0)
{
navigatebackward();
}
}
}
}
void main()
{
solvesudoku();
display();
}

Comments

Sign In or Register to comment.