【问题标题】:check 2d array diagonally?对角线检查二维数组?
【发布时间】:2017-05-23 10:04:33
【问题描述】:

我正在尝试对角搜索 3x3 二维数组,如下所示:

我想检查对角线中的所有框是否具有相同的值。以下是我尝试的方法:

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。但是代码并没有这样做,这是为什么呢?

【问题讨论】:

  • for(i = 0, j = 3-1; i &lt; 3; i++, j--) { if(board[i][j] != thisOne) { thisOne = '\0'; break; } }
  • @BLUEPIXY 哦,我现在明白为什么它不起作用了。谢谢!如果您希望我接受并投票,您可以回答问题。

标签: c arrays


【解决方案1】:

您只需要检查对角线单元格,而不是检查所有单元格。

【讨论】:

    【解决方案2】:

    当检索到第一个不匹配的字符时,您没有中断/退出检查循环。

    此外,您的嵌套 for 并不是您所猜测的:内部循环进入每一行的所有列,但您只想检查对角线值...

    您可以轻松简单的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)
    {
    }
    

    【讨论】:

      【解决方案3】:

      正如@BLUEPIXY 所说,问题在于j 循环嵌套在i 循环内。因此,对于i 循环中的每次迭代,j 循环在每一列上运行 3 次,而不是仅在次对角线上工作。有几种方法可以解决这个问题,但最理想的方法是只使用一个循环和一个变量i

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

      【讨论】:

        【解决方案4】:

        要实现您的目标,您只需在遍历数组时减少 X 迭代器和 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;
        }
        

        【讨论】:

          【解决方案5】:

          你可以这样做

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

          【讨论】:

          • 打印 I,j 值,您将获得所需的对角线索引 0,2 ; 1,1; 2,0
          【解决方案6】:

          你只能像这样检查对角线元素

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

          【讨论】:

            猜你喜欢
            • 2016-07-23
            • 2020-07-24
            • 2023-03-28
            • 1970-01-01
            • 2014-01-27
            • 1970-01-01
            • 2011-05-25
            • 2011-02-21
            • 1970-01-01
            相关资源
            最近更新 更多