尝试将int值与数组长度进行比较



我正在研究一个递归迷宫问题,我有三个选项:

  • 向前迈一步
  • 后退一步
  • 向前跳一定的步数

在数组中,15是已占用的空间,不能移动到那里。0是我旅行的开放空间。我认为我的代码几乎完成了,但是当我要离开数组时,我的代码中断了。下面是部分代码。这显示了我的方法,递归,我对应该发生的事情的注释,以及数组中的值。

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) {

我试图弄清楚如何输出true,如果改变将使迷宫[idx]的值大于arraySize变量的值,如果没有其他合法的移动(例如当数组读取1,1和a +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,0,1,1,0,1] with jump = 2返回false
  • [0, 1, 1, 0, 1, 0, 0, 1, 0, 1] with jump = 3返回true

终于想通了!可能有一种更精简的方法,但我在调试不同示例的过程中发现,我必须将if语句分开,因为我的||或|检查只查看第一个实例,如果第一个为假,则跳过另一个检查。程序有太多的选项,不能进行所有的检查,所以我必须创建多个if语句,并将它们按一定的顺序排列。

private static boolean solvable1DMaze(int maze[], int idx, int jump) {
// Create variable for array length.
int arraySize = maze.length;
// If the index + 1 is greater or equal to the arraySize then we can get out!
if ((idx + 1) >= arraySize) {
return true;
}
// If the index + 1 is empty then move to the empty slot.
if ((maze[idx + 1]) != 1) {
maze[idx] = 1; // Make the current place in the array 1 before we move to mark our spot.
return solvable1DMaze(maze, idx + 1, jump);
}
// If the index + jump is greater or equal to the arraySize then we can get out!
if ((idx + jump) >= arraySize) {
return true;
}
// If the index + jump is empty then jump the necessary spaces.
if ((maze[idx + jump]) != 1) {
maze[idx] = 1; // Make the current place in the array 1 before we move to mark our spot.
return solvable1DMaze(maze, idx + jump, jump);
}
if (idx > 0) {
// If the index - 1 is empty then back up one space.
if ((maze[idx - 1]) != 1) {
maze[idx] = 1; // Make the current place in the array 1 before we move to mark our spot.
return solvable1DMaze(maze, idx - 1, jump);
}
// Since we've already checked + 1, + jump, and - 1 to find no legal moves,
// return false to show we are trapped within the array with no valid moves
return false;
}
// If no valid moves can be triggered, return false.
return false;
}

最新更新