【发布时间】:2019-11-24 19:32:53
【问题描述】:
在迷宫运动中的老鼠中,当老鼠水平移动时,我遇到了问题。我已经将老鼠定义为首先向下移动(如果有的话),然后向右然后向左移动。问题在于,当它走到一条死胡同并试图找到赖特路径时,老鼠会混淆左右两边。路径存储在数组中。出口在底部的任何地方。老鼠可以向任何方向移动。 (0,3) 是开始。
0 = 免费通过
1 = 被阻止
请看下面的例子:
1 1 1 0 1 1 1
1 1 1 0 1 1 1
1 0 0 0 1 0 1
1 0 1 0 1 0 0
1 1 1 0 1 1 1
1 0 0 0 0 0 1
1 0 1 1 1 0 1
0 0 1 1 1 0 1
0 1 1 1 0 1 1
路径:(0,3) (1,3) (2,3) (3,3) (4,3) (5,3) (5,4) (5,5) (6,5) (7,5) (6,5) (5,5) (5,4) (5,5) (6,5) (7,5) (6,5) (5,5) (5,4) (5,5)...
在此示例中,位于 (5,4) 处的老鼠没有选择向左移动,而是循环前一个路径。 我真的在努力寻找解决方案。有人知道吗?
这是我的一些代码:
public boolean solveRatMaze(int maze[][], int x, int y, int sol[][], Stack stack) {
if ((x == maze.length-1 && isValidPlace(maze, x, y)) { //when (x,y) is the bottom right room
sol[x][y] = 0;
stack.push(String.valueOf(x));
stack.push(String.valueOf(y));
return true;
}
if(isValidPlace(maze, x, y) == true) { //check whether (x,y) is valid or not
sol[x][y] = 0; //set 0, when it is valid place
if (solveRatMaze(maze,x+1, y, sol, stack) == true) //when x direction is blocked, go for bottom direction
return true; //when x direction is blocked, go for bottom direction
if (solveRatMaze(maze, x, y + 1, sol, stack) == true) //find path by moving right direction
return true; //when x direction is blocked, go for bottom direction
if (solveRatMaze(maze, x, y - 1, sol, stack) == true) //find path by moving left direction
return true;
sol[x][y] = 0; //if both are closed, there is no path
return false;
}
return false;
}
isValidPlace 只检查地点是否在 数组,值为 0(非阻塞)
sol[][] 是一个表示最终路径的数组。所有值为 1 除了路径值为 0
maze[][] 是给定的数组
【问题讨论】:
标签: java backtracking maze