我正在尝试解决递归回溯问题,在这个问题中,我们必须从一个二维整数数组中的给定坐标开始,并找到一条到数组边缘单元格的路径,这样路径上的每个连续元素都小于或等于前一个元素(从给定元素开始)。如果当前单元格中的元素等于前一个元素,我不知道如何正确地回溯,所以我只使用了每个单元格中具有不同值的测试用例。任何帮助/评论都将不胜感激,这里是我目前为止的代码:
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;
}
}发布于 2020-01-05 20:26:43
请参阅我上面的评论,并添加一个跟踪您已经访问过的点的地图(因为不会再去那里了)。
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;
}
}https://stackoverflow.com/questions/59591606
复制相似问题