2017-05-23 73 views
3

我想對角搜索一個3x3的二維數組,像這樣:enter image description here對角檢查2d陣列?

我要檢查,如果在對角線所有箱子具有相同的值。這裏是我嘗試這樣做:

thisOne = board[0][2]; //set to 'X' 
    for(i = 0; i<3; i++) { 
     for(j = 3; j>0; j--){ 
      if(board[i][j-1] != thisOne) { 
       thisOne= '\0'; 
      } 
     } 
    } 
//since all boxes were 'X', thisOne is still set to 'X' 
if(thisOne != '\0') { 
    winner = thisOne; 
    printf("vinnare på nördöst\n"); 
} 

所以運行此代碼後,winner應該是「X」,如果所有的箱子是X的。但是代碼不這麼做,爲什麼?

+2

'爲(I = 0,J = 3-1; I <3;我++,j--){如果(!板[i] [j] = thisOne){thisOne = '\ 0' ;打破; }}' – BLUEPIXY

+0

@BLUEPIXY哦,我現在看到它爲什麼不起作用。謝謝!如果您希望我接受和贊成,您可以回答這些問題。 – Carlton

回答

1

您只需檢查對角線單元而不是檢查所有單元。

1

當檢索到第一個不匹配的字符時,您不打破/退出檢查循環。

而且你的嵌套不至於你猜是什麼:內環路一個到每個行的所有列,但你要車只有對角線值...

您可以輕鬆簡單的while

int i=0; 
int j=2; 
while ((i<3) && (j>=0) && (board[i][j] == thisOne)) 
{ 
    i++; 
    j--; 
} 

// if i<3 the diagonal is not full of thisOne char 
if (i < 3) 
{ 
} 
0

要實現您的目標,您只需在遍歷數組時通過X iterator & Y迭代器遞減。

下面是一個簡單的例子:

#include <stdio.h> 
#include <stdlib.h> 

int  main(void) 
{ 
    int arr[3][3]; 
    int it_y; 
    int it_x; 

    it_y = 0; 
    it_x = 2; 
    arr[0][0] = 0; 
    arr[0][1] = 1; 
    arr[0][2] = 2; 
    arr[1][0] = 3; 
    arr[1][1] = 4; 
    arr[1][2] = 5; 
    arr[2][0] = 6; 
    arr[2][1] = 7; 
    arr[2][2] = 8; 
    while (it_x < 3 && it_x >= 0) 
    { 
     printf("[%d][%d]: '%d'\n", it_y, it_x, arr[it_y][it_x]); 
     --it_x; 
     ++it_y; 
    } 
    return EXIT_SUCCESS; 
} 
0

你可以這樣做

for(int row=0,col=2; row<3; row++,col--) 
{ 
    if(board[row][col] != thisOne) 
    { 
      thisOne= '\0'; 
    } 
} 
+0

打印I,j值將得到所需的對角索引0,2; 1,1; 2,0 – Krishnan

0

您只能檢查對角線元素這樣

for(i = 0, j = 3-1; i < 3; i++, j--) { 
    if(board[i][j] != thisOne) { 
     thisOne = '\0'; 
    } 
} 
1

正如@BLUEPIXY說,問題在於j循環嵌套在i循環。因此,對於i循環中的每次迭代,j循環在每列上運行3次,而不是僅處理次要對角線。有幾種方法可以解決這個問題,儘管最理想的方法是隻使用一個單一的循環和只有一個變量i

for(i=0;i<3;i++) { 
    if(board[i][2-i]!=thisOne) { 
     thisOne='\0' 
     break; 
    } 
}