繁体   English   中英

如何获取二维数组中某个点的所有邻居?

[英]How to get all the neihbors neighbors of a point in a 2d array?

我正在尝试获取二维数组中简单的一个字符串组合的所有邻居。 意思是,我的 output 目前在 3x5 中看起来像这样:

A B C
D E F
A S D 
F S A
G S A

所以(1,0)的邻居应该是= ABES A。目前我有以下内容:

public void getNeighborsOfPoint(int x, int y) {

        for (int xx = -1; xx <= 1; xx++) {
            for (int yy = -1; yy <= 1; yy++) {
                if (xx == 0 && yy == 0) {
                    continue; // You are not neighbor to yourself
                }
                if (Math.abs(xx) + Math.abs(yy) > 1) {
                    continue;
                }
                if (isOnMap(x + xx, y + yy)) {
                    System.out.println(grid[x+xx][y+yy]);
                }
            }
        }
   

 public boolean isOnMap(int x, int y) {
        return x >= 0 && y >= 0 && x < length && y < width;
    }

但是,在我提供的示例中,它只返回 AEA。(它不返回交叉的)使它工作的正确代码是什么? 请注意,输入并不总是 3 x 5。它可能是 x 和 y 的很多不同组合。

由于此代码,不包括对角线:

if (Math.abs(xx) + Math.abs(yy) > 1) {
    continue;
}

当它在对角线上时Math.abs(xx) == 1 && Math.abs(yy) == 1 所以它们的总和将大于 1。您可以通过在此处使用此代码来跳过对角线。

您没有在当前组中获得对角线的原因是第二个if语句。 例如,您需要覆盖(2, 1) ,即xx1yy1时。 但是abs(1) + abs(1) = 2 and 2 > 1 ,所以你不包括它。

作为重构练习,如果将 for 循环的内部简化为一个条件,它可能会更清晰一些。

if (expression) { 
    continue 
}; 
// other stuff

相当于

if (!expression) {
  // other stuff.
}

对你来说, expression (在伪代码中) not(xx=0 and yy=0) and isOnMap(xx, yy)

在循环中, continue关键字意味着您将跳到循环的下一次迭代。 在你的情况下,你有:

            if (Math.abs(xx) + Math.abs(yy) > 1) {
                continue;
            }
            if (isOnMap(x + xx, y + yy)) {
                System.out.println(grid[x+xx][y+yy]);
            }

因此,如果第一个条件得到验证,您将不会打印任何答案,这意味着您的程序不会将 A(xx, yy) 视为邻居。

在您的 ABESA 示例中,B 和 S 因此被忽略。

如果你想使用 2d arrays 和可变数量的行和列,你必须将它们作为参数传递给你的isOnMap方法,如下所示:

public static boolean isOnMap(int x, int y, int length, int width) {
    return x >= 0 && y >= 0 && x < length && y < width;
}

您可以处理二维数组的特殊情况(当您的元素的行号和列号之一或两者等于 0 时)以这种方式重写您的getNeighborsOfPoint方法:

public static void getNeighborsOfPoint(int x, int y, char[][] grid) {
    final int length = grid.length;
    final int width = grid[0].length;

    if (isOnMap(x, y, length, width)) {

        for (int i = Math.max(0, x - 1); i < Math.min(length, x + 2); ++i) {
            for (int j = Math.max(0, y - 1); j < Math.min(width, y + 2); ++j) {

                if (i != x || j != y) {
                    System.out.println(grid[i][j]);
                }
            }
        }
    }
}

暂无
暂无

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

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