首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归回溯2D数组(水会从地图上掉下来吗)

递归回溯2D数组(水会从地图上掉下来吗)
EN

Stack Overflow用户
提问于 2020-01-04 22:25:19
回答 1查看 401关注 0票数 0

我正在尝试解决递归回溯问题,在这个问题中,我们必须从一个二维整数数组中的给定坐标开始,并找到一条到数组边缘单元格的路径,这样路径上的每个连续元素都小于或等于前一个元素(从给定元素开始)。如果当前单元格中的元素等于前一个元素,我不知道如何正确地回溯,所以我只使用了每个单元格中具有不同值的测试用例。任何帮助/评论都将不胜感激,这里是我目前为止的代码:

代码语言:javascript
复制
public static boolean canFlowOffMap(int[][] map, int row, int col) {
    int current = map[row][col];
    return mthd6(map, current, row, col, false);
}

private static int[][] OPTIONS = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };

private static boolean mthd6(int[][] map, int current, int r, int c, boolean result) {
    if (r == 0 || c == 0 || r == map.length -1 || c == map[0].length -1) {
        return true;
    } else {
        for (int[] option : OPTIONS) {
            r += option[0];
            c += option[1];
            if (map[r][c] < current) {
                current = map[r][c];
                result = mthd6(map, current, r, c, false);
            }
            r -= option[0];
            c -= option[1];
        }
        return result; 
    }
}
EN

回答 1

Stack Overflow用户

发布于 2020-01-05 20:26:43

请参阅我上面的评论,并添加一个跟踪您已经访问过的点的地图(因为不会再去那里了)。

代码语言:javascript
复制
private static boolean mthd6(int[][] map, int r, int c, List<Point> visited) {
  int current = map[row][col];
  visited.add(new Point(r, c));
  if (r == 0 || c == 0 || r == map.length -1 || c == map[0].length -1) {
    return true;
  } else {
    for (int[] option : OPTIONS) {
        r += option[0];
        c += option[1];
        if (!visited.contains(new Point(r, c) && map[r][c] <= current) {
            result = result || mthd6(map, r, c);
        }
        r -= option[0];
        c -= option[1];
    }
    return result; 
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59591606

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档