首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查同一行或同一列中是否存在相同的数字

检查同一行或同一列中是否存在相同的数字
EN

Stack Overflow用户
提问于 2012-06-24 20:19:29
回答 1查看 1.8K关注 0票数 0

我已经盯着这段代码看了几个小时,尝试了演练,调试了汽车和断点,但到目前为止还没有解决方案。也许某人的新鲜感会对我有帮助;)。

代码语言:javascript
复制
#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。这个程序是数独解算器的一部分。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-06-24 20:27:14

您在if语句中混淆了索引。它们应该是:

代码语言:javascript
复制
if(checkedValue==matrix[i][column]) return false; // not matrix[column][i]

代码语言:javascript
复制
if(checkedValue==matrix[row][i]) return false;    // not matrix[i][row]

原因是第一个维度是行。可以通过打印matrix[2][0]来检查这一点。

对于您的矩阵,您将得到2(而不是6)。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11177378

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档