【发布时间】:2021-11-14 15:55:41
【问题描述】:
我正在研究一个递归迷宫问题,我有三个选项:
- 向前迈出一步
- 后退一步
- 向前跳跃一定的步数
在数组内部,1 是被占用的空间,我不能去那里。 0是我旅行的开放空间。我认为我的代码几乎完成了,但是当我要离开数组时,我的代码会中断。这是代码的一部分。这显示了我的方法、递归、我的 cmets 应该发生的事情以及数组中的值。
System.out.println(solvable1DMaze(new int[] { 0, 1, 0, 0, 1 }, 0, 2));
private static boolean solvable1DMaze(int maze[], int idx, int jump) {
// Create variable for array length.
int arraySize = maze.length;
// If the index + 1 is empty then move to the empty slot.
if ((maze[idx + 1]) != 1) {
return solvable1DMaze(maze, idx + 1, jump);
}
// If the index - 1 is empty then back up one space.
if (maze[idx] > 0 && (maze[idx - 1]) != 1) {
return solvable1DMaze(maze, idx - 1, jump);
}
// If the index + jump is empty then jump the necessary spaces.
if ((maze[idx + jump]) != 1 && maze[idx + jump] < arraySize) {
return solvable1DMaze(maze, idx + jump, jump);
}
// If we leave the array, return true.
if (maze[idx] > arraySize) {
return true;
// Otherwise, return false.
} else {
return false;
}
}
这是它当前崩溃的行:
if ((maze[idx + jump]) != 1 && maze[idx + jump] < arraySize) {
如果更改将使 maze[idx] 的值大于 arraySize 变量的值,我试图弄清楚如何输出 true,如果没有其他合法移动(例如当数组读取1, 1 和 +1 或跳跃不能落在 0) 上,表明数组是不可避免的。
这些是我得到的其他测试数组,以确保我的算法有效:
- [0, 1, 0, 0, 1] with jump = 2 返回 true
- [0, 1, 1, 0, 1] with jump = 2 返回 false
- [0, 1, 0, 0, 0, 1, 1, 0, 1] with jump = 2 返回 false
- [0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1] with jump = 3 返回真
【问题讨论】:
-
“中断”是什么意思?您的 if 语句不检查
idx + jump的结果是否小于maze.length。 -
崩溃时中断。该程序停止使用“ArrayIndexOutOfBoundsException”。我告诉它检查 idx + jump 是否小于 maze.length 就在这里:
if ((maze[idx + jump]) != 1 && maze[idx + jump] < arraySize) {除非我需要取出 maze[] 部分并直接向上(idx + jump) < arraySize -
是的,这就是你需要做的检查数组索引是否在边界内(在上端)
-
我认为这里可以进行优化。应该有很多重复的调用。您可以使用 Map 来存储调用结果。然后检查当前调用是否已经计算(如果它在地图中)