2017-05-23 76 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; 
    } 
}