我已经盯着这段代码看了几个小时,尝试了演练,调试了汽车和断点,但到目前为止还没有解决方案。也许某人的新鲜感会对我有帮助;)。
#include <iostream>
using namespace std;
int matrix[9][9] = {{0, 0, 6, 0, 0, 0, 1, 0, 5},
{0, 4, 0, 7, 0, 6, 0, 3, 9},
{2, 0, 0, 9, 3, 0, 6, 0, 0},
{7, 0, 0, 1, 8, 0, 5, 0, 4},
{0, 0, 4, 0, 6, 0, 9, 0, 0},
{1, 0, 9, 0, 5, 2, 0, 0, 3},
{0, 0, 1, 0, 9, 3, 0, 0, 7},
{6, 7, 0, 5, 0, 8, 0, 9, 0},
{9, 0, 8, 0, 0, 0, 4, 0, 0}};
bool check(int column ,int row,int checkedValue)
{
//column check
for(int i=0; i<9; i++)
{
if(i==row)continue;
if(checkedValue==matrix[column][i]) return false;
}
//row check
for(int i=0; i<9; i++)
{
if(i==column) continue;
if(checkedValue==matrix[i][row]) return false;
}
return true;
}
int main()
{
cout<<check(4,0,4); //Why does it output 0? There is no "4" in the 5th column and the 1st row.
system("pause");
return 0;
}函数check(column,row,value)被设计为当number在“矩阵”二维表中至少出现一次时返回0。这个程序是数独解算器的一部分。
发布于 2012-06-24 20:27:14
您在if语句中混淆了索引。它们应该是:
if(checkedValue==matrix[i][column]) return false; // not matrix[column][i]和
if(checkedValue==matrix[row][i]) return false; // not matrix[i][row]原因是第一个维度是行。可以通过打印matrix[2][0]来检查这一点。
对于您的矩阵,您将得到2(而不是6)。
https://stackoverflow.com/questions/11177378
复制相似问题