#include <stdio.h>
#include <stdlib.h>
#define R 4
#define C 5
// functions for option 1 initializeCountArray and TestCount and Sudoku
void initializeCountArray(int *count)
{
int i;
for (i = 0; i < 10; i++)
count[i] = 0;
}
int TestCount(int *count)
{
int i;
for (i = 1; i < 10; i++)
if ( count[i] == 1)
count[0]++;
return 1;
}
int Sudoku(int mat[R][C])
{
int count[10] = { 0 };
int rows,cols,i,j;
for(rows=0; rows<R-2; rows++)
{
for (cols = 0; cols<C-2; cols++)
{
initializeCountArray(count);
for (i = rows; i <= rows+2; i++)
{
for (j = cols; j <= cols+2; j++)
{
count[ mat[i][j] ] ++;
printf("\n%d,%d",i,j);
}
}
printf("\n TestCount=%d",TestCount(count));
if (TestCount(count) == 9)
return 1;
}
}
return 0;
}
void main ()
{
int mat[R][C] = {{1,7,8,9,6},
{1,3,3,4,6},
{1,1,1,2,5},
{1,6,7,8,9}};
printf ("\n Check Matrix if Suduku 3X3 square found");
if (Sudoku(mat) == 1)
printf("\n Sudoku square matrix was found\n");
else
printf("\n Sudoku square matrix NOT found\n");
}
此程序应解决我们在课堂上通过包含的功能进行的特定代码测试并且我们无法在运行程序时使用其他方法,TestCount函数给出错误的数字作为输出,我使用了索引的测试打印输出,并且我无法弄清楚出了什么问题,请帮助
首先:
在TestCount
函数中,将count[0]
用作3x3子矩阵中出现的数字的计数器。我想你想做:
return count[0];
而不是您的:
return 1;
第二,您执行此操作:
printf("\n TestCount=%d", TestCount(count));
if (TestCount(count) == 9)
return 1;
但是请注意,您的TestCount
有一些副作用。第一次调用它,对于Sudoku样式的3x3矩阵,count[0]
将得到9,但是第二次您继续递增count[0]
,因此它将得到18,并且无法通过== 9
检查-最终,您的Sudoku
函数错过了。
您可能应该在count[0] = 0;
的调用之间设置TestCount()
,在开始计算count[0]
之前将TestCount()
重置为0或您可能想到的其他方式(只需确保您不覆盖它)。