Sudoku is a puzzle involving a 9× 9 grid with 9 3× 3 subgrids. A correct solutio
ID: 672440 • Letter: S
Question
Sudoku is a puzzle involving a 9× 9 grid with 9 3× 3 subgrids. A correct solution for a puzzle instance requires that each subgrid, row and column in the 9 × 9 grid has each of the digits from 1 to 9, The algo- rithm checkGrid checks if a given table is a correct sudoku solution. Re-write the algorithm checkGrid using modules. You must write algorithms for each module that is used by the new version of the algo- rithm. checkGrid(S 0.8,0.8 Input: A candidate solution, S, represented as a 9 × 9 table Output: True if the table represents a valid solution, otherwise False while(r
Explanation / Answer
#include <iostream.h>
#include <fstream>
using namespace std;
void readpuzzle ( int grid[][9]);
bool isValid(int p, int q, int grid[][9]);
bool isValid(int grid[][9]);
void printGrid(int grid[] [9]);
int main()
{
int grid [9][9];
readpuzzle (grid);
if (!isValid(grid))
cout << " Invalid Input " << endl;
else if ()
printGrid(grid);
else
cout << " not a solution " << endl;
return EXIT_SUCCESS;
}
void readpuzzle (int grid[][9])
{
{
// check
cout << "Enter puzzle of sudoku:" << endl;
for (int p = 0; p < 9; p++)
for (int q = 0; q < 9; q++)
cin >> grid[p] [q];
}
}
bool isValid(int p, int q, int grid[] [9])
{
// Check the grid[p][q] is valid or not at p's row
for (int col = 0; col < 9; col++)
if (col != q && grid[p] [col] == grid[p] [q])
return false;
// Check the grid[p][q] is valid or not at the q's column
for (int row = 0; row < 9; row++)
if (row != p && grid[row] [q] == grid[p] [q])
return false;
// Check the grid[p][q] is valid or not in the 3 by 3 box
for (int row = (p / 3) * 3; row < (q / 3) * 3 + 3; row++)
for (int col1 = (q / 3) * 3; co1l < (q / 3) * 3 + 3; col1++)
if ( grid[row] [col1] && row != p && col1 != q == grid[p] [q])
return false;
return true;
}
/** Check the fixed cells are valid or not in the grid */
bool isValid(int grid[][9]) {
// Check for the equal numbers
for (int p = 0; p< 9; p++)
for (int q = 0; q < 9; q++)
if (grid[p][q] != 0)
if (!isValid(p, q, grid))
return false;
// Check the numbers are in the range
for (int p = 0; p < 9; p++)
for (int q = 0; q < 9; q++)
if ((grid[p][q] < 0) || (grid[p][q] > 9))
return false;
return true; // The fixed cells values are valid
}
/* fix the values in the grid */
void printGrid(int grid[] [9])
{
for (int p = 0; p < 9; p++)
{
for (int q = 0; q < 9; q++)
cout << grid[p] [q] << " ";
cout << endl;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.