java - 寻找二维数组中的最小邻居

标签 java multidimensional-array

我有一些代码应该找到 2D 数组中 8 个相邻单元格中最小的一个。当此代码运行时,将移动到最小的值,然后代码再次循环运行。然而,当它运行时,代码最终会给出堆栈溢出错误,因为它不断在两点之间跳转。这似乎是一个逻辑悖论,好像 Y < X 那么 X !< Y。所以它认为这是我的代码错误,而不是我的逻辑错误。这是我的代码:

private Point findLowestWeight(Point current) {
    float lowest = Float.MAX_VALUE;
    Point ret = new Point(-1, -1);
    LinkedList<Point> pointList = new LinkedList<Point>();
    for (int i = -1; i <= 1; i++) {
        for (int j = -1; j <= 1; j++) {
            if (!(i == 0 && j == 0)) {
                if ((current.x + i >= 0 && current.x + i <= imageX - 2) 
                 && (current.y + j >= 0 && current.y + j <= imageY - 2)) {
                    pointList.add(new Point(current.x + i, current.y + j));
                }
            }
        }
    }
    for (Point p : pointList){
        if (map[p.x][p.y] < lowest){
            lowest = map[p.x][p.y];
            ret = p;
        }
    }
    return ret;
}

最佳答案

你需要一个停止案例。

find the smallest of the 8 neighboring cells in a 2D array. When this code runs, the smallest is then moved to, and the code run again in a loop

这是一个很好的开始方式,但没有提到停止。

你关心当前单元格的值吗?如果是这样,您需要检查 9 而不是 8。如果您只是想下山,那么您需要检查您去过的地方,否则任何平坦的多单元山谷都会让您陷入无限循环。仅在向下移动时才考虑移动。

如果你真的不在乎你在哪里,那么即使是一个单细胞谷也会让你在你弹进弹出时陷入无限循环。在这种情况下,您需要一些其他停止条件。考虑在 imageX * imageY 迭代后停止。

关于java - 寻找二维数组中的最小邻居,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29590436/

相关文章:

java - JFormattedTextField 未正确清除

java - Spring Data MongoDB 聚合与日期和平均值匹配

java - 我无法创建 Eclipse Java 类

javascript - 循环显示分层数据

java - 在 spring 集成中如何仅使用 java 注释配置消息网关,并确保网关看到回复

java - volley json 数组只获取最后一个元素

java - 遍历 n 维数组

Java初始化二维数组列表

arrays - 将日期和整数合并到 ARRAY 中

c - 在 C 中使用指针打印二维数组