java - 递归回溯二维数组(水会从地图上掉下来)
问题描述
我正在尝试解决递归回溯问题,其中我们必须从二维整数数组中的给定坐标开始,并找到到数组边缘单元的路径,使得沿路径的每个连续元素小于或等于到前一个(从给定元素开始)如果当前单元格中的元素等于前一个元素,我不知道如何正确回溯,所以我只使用每个单元格中具有不同值的测试用例。任何帮助/评论将不胜感激这是我到目前为止的代码:
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;
}
}
解决方案
请参阅我上面的评论,并添加一个跟踪您已经访问过的点的地图(因为没有再去那里的意义)。
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;
}
}
推荐阅读
- linux-kernel - 如何在内核模块版本魔术中添加 SMP 和 Preempt?
- java - Apache Flink、JDBC 和 fat jar 是否存在类加载问题?
- entity-relationship - 你如何触发(多对多)表和普通表之间的一对多关系?
- google-bigquery - 如何通过另一列的特定 ID 连接一列?
- azure - ASP.NET Core 纯文本基准测试难题
- unity3d - 烟雾粒子不连续播放
- python - 从 spacy 包运行模型时出现错误消息
- r - 具有函数“seq”的 data.table 中的错误是什么意思——“RHS 长度必须为 1 或与 LHS 长度完全匹配”?
- angular - 为什么 (click)="handleEdit()" 在这里不起作用
- c - 我可以在主代码中弹出链表的第一个元素(char),但我不能把这部分代码放在函数中