2012-06-24 44 views
0

我一直盯着這段代碼幾個小時,嘗試過演練,使用汽車和斷點進行調試,到目前爲止它還沒有解決方案。 Maybie某人的新面貌會幫助我;)。檢查數字是否存在於同一行或列中

#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; 
} 

函數檢查(列,行,值)被設計爲在「矩陣」二維表中至少出現一次時返回0。這個程序是一個數獨解算器的塊。

+2

你可以擴展你正在嘗試做什麼?您是否嘗試檢查相同的數字是否多次出現在同一列/行中。看看你的代碼,看起來你可能正在編寫一個Sudoku求解器,但這只是一個猜測。 – JPvdMerwe

回答

3

您在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)。

相關問題