【问题标题】:Count adjacent numbers in a 2D array计算二维数组中的相邻数字
【发布时间】:2021-02-15 03:53:35
【问题描述】:

我正在尝试遍历 2D 数组的元素并计算与用户选择的正方形相邻的 1 的数量。我无法在直接接触所选方格的 9 个方格中整理出 1。下面的代码显示了reveal(int row, int col) 命令。此外,下面显示了一个可以使用的二维数组的示例。

/** 
 * The reveal command. Reveals the user inputted square and displays the number of
 * the number of mines adjacent to the square.
 */
pubic void reveal(int row, int col) {
   int minesTouching = 0;
   for (int x = 0; x < this.rows; x++) {
       for (int y = 0; y < this.cols; y++) {
           if (this.grid[x][y] == 1) {
              minesTouching++;
           } // if
       } // for
   } // for
   this.userGrid[row][col] = String.valueOf(minesTouching);
} // reveal

这是reveal命令的方法

int[][] grid = {1 0 0 0},
               {0 1 0 0},
               {0 0 1 0},
               {0 0 0 1};

这是 int 形式的 mineField,其中 1 是地雷,0 是非地雷。我在reveal() 中使用这个网格来检查地雷相对于用户选择的方格的位置。然而,当打印到屏幕上时,我使用userGrid[][],它是一个字符串数组,可以保存我拥有的一些其他命令以及相邻地雷的数量。输出应如下所示:。

我想遍历数组中的所有元素,但只计算所选正方形的直接 9 中的 1。任何帮助将不胜感激,如果您需要更多详细信息,请告诉我。谢谢!

【问题讨论】:

  • 我觉得这个问题需要更清楚,有问题你说的是与选定的正方形相邻,但在方法中你要遍历从开始到正方形的所有元素,例如如果我说相邻(1,2) = (0,1), (0,2),(0,3),(1,1),(1,3),(2,1),(2,2),( 2,3) 但根据你的方法,你正在经历所有像 (0,0),(0,1),(0,2),(0,3),(1,0),(1,1)

标签: java arrays


【解决方案1】:

不是最优雅的,但我猜是最简单的解决方案:

      public void review(int row, int col){
          int minesTouching;
          for(int i=row-1;i<=row+1;i++){
           for(int j=col-1;j<=col+1;j++){
            if(grid[i][j]==1){
             minesTouching++
            }
           }      
          }
        }

(我假设正方形 [row][col] 之前已经检查过不包含地雷) 我希望这能回答你的问题

【讨论】:

  • 您必须检查第 - 1 行不小于零且第 + 1 行不大于行长 - 1。您必须对列执行相同的检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 2012-12-30
  • 2021-01-19
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
相关资源
最近更新 更多