Write a C++ function to test whether a given 9x9 matrix contains a valid Sudoku
ID: 3545358 • Letter: W
Question
Write a C++ function to test whether a given 9x9 matrix contains a valid Sudoku
configuration. The function should return 1 if the configuration is valid and 0 otherwise.
If you are not familiar with the rules of Sudoku, Wikipedia has a good summary:
http://en.wikipedia.org/wiki/Sudoku. The input matrix could be complete or
incomplete.
A complete matrix has all cells filled with numbers.
Notes:
- Only submit your source code (.cpp). This must be done on or before the due date
- Once again, no late submissions.
- Your program must include comments explaining your steps.
due Oct 30,2013
Explanation / Answer
int sudoku(int matrix[9][9])
{
int r, c, r1, c1, i;
int fill[9];
// check each row
for (r = 0; r < 9; r++)
{
// initialize fill to 0
for (i = 0; i < 9; i++)
fill[i] = 0;
// test each number in the row
for (c = 0; c < 9; c++)
{
int v = matrix[r][c];
if (v < 1 || v > 9 || fill[v-1] > 0)
return 0;
fill[v-1] = 1;
}
}
// check each column
for (c = 0; c < 9; c++)
{
for (i = 0; i < 9; i++)
fill[i] = 0;
for (r = 0; r < 9; r++)
{
int v = matrix[r][c];
if (v < 1 || v > 9 || fill[v-1] > 0)
return 0;
fill[v-1] = 1;
}
}
// check each box
r = c = 0;
while (r < 9)
{
for (i = 0; i < 9; i++)
fill[i] = 0;
for (r1 = 0; r1 < 3; r1++)
{
for (c1 = 0; c1 < 3; c1++)
{
int v = matrix[r+r1][c+c1];
if (v < 1 || v > 9 || fill[v-1] > 0)
return 0;
fill[v-1] = 1;
}
}
c += 3;
if (c >= 9)
{
c = 0;
r += 3;
}
}
return 1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.