【发布时间】: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)