繁体   English   中英

如何在2D数组中检查对角邻域并将当前值设置为等于邻域数

[英]How To Check For Diagonal Neighbors in a 2D Array and Set Current Value Equal to Number of Neighbors

我试图遍历2D数组并计算所有等于0的对角线邻居,然后将当前位置设置为等于邻居数。 例如:

0 5 0 9
0 5 0 3
1 9 4 6
7 0 0 9

应该更改为

0 2 0 1 
0 3 1 2 
1 3 1 2
0 1 1 1

我正在使用以下代码(我捕获异常,因为所有参数编号都将超出索引范围):

int row, col, count;
        count = 0;
// Standard for-loop used in walking through a 2D array
        for (row = 0; row < NUM; row++) {
            for (col = 0; col < NUM; col++) {
               // Check top left neighbor
               try {
                    if (grid[row - 1][col - 1] == 0) {
                        count++;

                    }
                } catch (IndexOutOfBoundsException e) {

                } // Check bottom left neighbor
                try {
                    if (grid[row - 1][col + 1] == 0) {
                        count++;

                    }
                } catch (IndexOutOfBoundsException e) {

                } // Check top right neighbor
                try {
                    if (grid[row + 1][col - 1] == 0) {
                        count++;

                    }
                } catch (IndexOutOfBoundsException e) {

                } // Check bottom right neighbor
                try {
                    if (grid[row + 1][col + 1] == 0) {
                        count++;

                    }
                } catch (IndexOutOfBoundsException e) {

                } // Set current place in the array equal to number of 0 neighbors
                grid[row][col]=count;
                count = 0;

            }

        }

问题是我的输出错误。 代替假定的代码,它更改为以下内容:

0 2 0 1 
0 3 1 2 
1 2 1 1 
0 0 0 0 

因此,前两行有效,然后第三行具有多个OBO错误。 不知道最后一行到底有什么问题,也不确定哪里出了问题。

摘要

原来是:

0 5 0 9
0 5 0 3
1 9 4 6
7 0 0 9

那应该变成:

0 2 0 1 
0 3 1 2 
1 3 1 2
0 1 1 1

但是我得到了:

0 2 0 1 
0 3 1 2 
1 2 1 1 
0 0 0 0

另一个示例将是:

原版的:

5 0 0 3 9 5 
0 0 9 5 3 0 
0 0 0 9 7 3 
7 0 5 0 9 5 
0 0 3 0 0 0 
9 5 0 3 7 0 

更新:

1 1 1 0 1 0 
1 2 2 1 2 0 
1 0 2 0 2 0 
2 1 4 1 4 1 
0 1 0 1 1 0 
0 2 0 1 1 0 

任何建议将不胜感激。

你开始

0 5 0 9
0 5 0 3
1 9 4 6
7 0 0 9

您从左上角开始遍历并同时修改矩阵。 因此,在修改2行之后,中间矩阵为

0 2 0 1 
0 3 1 2 
1 9 4 6
7 0 0 9

现在考虑index [2][1]处的元素。 在原始矩阵中,它有3 zero neighbors ,但是此矩阵只有2 ,因此期望和获得的输出之间存在差异。

制作一个单独的矩阵来存储修改后的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM