Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Sudoku Solver, Using this code, how would I output the solution? #include using namespace std; #define UNASSIGNED 0 #define N 9 int row, col; bool

Sudoku Solver, Using this code, how would I output the solution?

#include

using namespace std;

#define UNASSIGNED 0

#define N 9

int row, col;

bool EmptyCell(int grid[9][9], int &row, int &col);

bool isSafe(int grid[9][9], int row, int col, int num);

bool SolveSudoku(int grid[9][9])

{

int row, col;

if (!EmptyCell(grid, row, col))

return true;

for (int num = 1; num <= 9; num++)

{

if (isSafe(grid, row, col, num))

{

grid[row][col] = num;

if (SolveSudoku(grid))

return true;

grid[row][col] = UNASSIGNED;

}

}

return false;

}

bool EmptyCell(int grid[9][9], int &row, int &col)

{

for (row = 0; row < 9; row++)

for (col = 0; col < 9; col++)

if (grid[row][col] == UNASSIGNED)

return true;

return false;

}

bool UsedInRow(int grid[9][9], int row, int num)

{

for (int col = 0; col < N; col++)

if (grid[row][col] == num)

return true;

return false;

}

bool UsedInCol(int grid[9][9], int col, int num)

{

for (int row = 0; row < N; row++)

if (grid[row][col] == num)

return true;

return false;

}

bool UsedInBox(int grid[9][9], int boxStartRow, int boxStartCol, int num)

{

for (int row = 0; row < 3; row++)

for (int col = 0; col < 3; col++)

if (grid[row+boxStartRow][col+boxStartCol] == num)

return true;

return false;

}

bool isSafe(int grid[9][9], int row, int col, int num)

{

return !UsedInRow(grid, row, num) &&

!UsedInCol(grid, col, num) &&

!UsedInBox(grid, row - row%3 , col - col%3, num);

}

void printGrid(int grid[9][9])

{

for (int row = 0; row < N; row++)

{

for (int col = 0; col < 9; col++)

//printf("%2d", grid[row][col]); cout << grid[row][col] << endl;

//printf(" ");

}

}

int main()

{

int grid[9][9];

// 0 means unassigned cells

cout<<"Enter cells"<

for(int i=0;i<9;i++)

{

for(int j=0;j<9;j++)

cin>>grid[i][j];

}

if (SolveSudoku(grid) == true)

{

cout<<"solution exists"<

cout << << endl;

}

else

cout << "No Solution." << endl;

return 0;

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions