我正在研究一种递归求解由单元格组成的方法。
该方法完全行不通。任何建议,将不胜感激。
参数:srow = 起始 x 值。scol = 凝视 y 值 erow = 结束 x 值。ecol = 结束 y 值。L = 已解决路径点的链表
代码:
private InputGraphicMaze2 maze;
private int R, C;
//code added by me
private String[] [] cell; //an array to keep track of cells that are proven dead ends.
public YourMazeWithPath2()
{
// an R rows x C columns maze
maze = new InputGraphicMaze2();
R=maze.Rows(); C=maze.Cols();
//code added by me
cell = new String[R+2][C+2];
for (int i=0; i<R+2; i++) {
for (int k=0; k<C+2; k++) {
cell[i][k] = "no";
}
}
// Path holds the cells of the path
LinkedList<Point> Path = new LinkedList<Point>();
// Create the path
CreatePath(maze, 1, 1, R, C, Path);
// show the path in the maze
maze.showPath(Path);
}
private void setDead(int x, int y) {
cell[x][y] = "dead";
}
private void setVisited(int x, int y) {
cell[x][y] = "visited";
}
public boolean CreatePath(InputGraphicMaze2 maze,
int srow, int scol, int erow, int ecol, LinkedList<Point> L)
{
int x = srow;
int y = scol;
Point p = new Point(x, y);
if ((x<1) || (y<1) || (x>R) || (y>C)) {
return false; //cell is out of bounds
}
else if ((x==R) && (y==C)) {
return true; // cell is the exit cell
}
else {
if ((maze.can_go(x, y, 'U')) && (x!=1) && (!cell[x-1][y].equals("dead")) && (!cell[x-1][y].equals("visited"))) {
L.addLast(p);
setVisited(x,y);
CreatePath(maze, x-1, y, R, C, L);
return false;
}
else if ((maze.can_go(x, y, 'R')) && (y!=C) && (!cell[x][y+1].equals("dead")) && (!cell[x][y+1].equals("visited"))) {
L.addLast(p);
setVisited(x, y);
CreatePath(maze, x, y+1, R, C, L);
return false;
}
else if ((maze.can_go(x, y, 'D')) && (x!=R) && (!cell[x+1][y].equals("dead")) && (!cell[x+1][y].equals("visited"))) {
L.addLast(p);
setVisited(x, y);
CreatePath(maze, x+1, y, R, C, L);
return false;
}
else if ((maze.can_go(x, y, 'L')) && (y!=1) && (!cell[x][y-1].equals("dead")) && (!cell[x][y-1].equals("visited"))) {
L.addLast(p);
setVisited(x, y);
CreatePath(maze, x, y-1, R, C, L);
return false;
}
else {
if ((maze.can_go(x, y, 'U')) && (x!=1) && (cell[x][y-1].equals("visited"))) {
setDead(x, y);
if (L.contains(p))
L.remove(p);
CreatePath(maze, x-1, y, R, C, L);
return false;
}
else if ((maze.can_go(x, y, 'R')) && (y!=C) && (cell[x][y+1].equals("visited"))) {
setDead(x, y);
if (L.contains(p))
L.remove(p);
CreatePath(maze, x, y+1, R, C, L);
return false;
}
else if ((maze.can_go(x, y, 'D')) && (x!=R) && (cell[x+1][y].equals("visited"))) {
setDead(x, y);
if (L.contains(p))
L.remove(p);
CreatePath(maze, x+1, y, R, C, L);
return false;
}
else if ((maze.can_go(x, y, 'D')) && (y!=1) && (cell[x][y-1].equals("visited"))) {
setDead(x, y);
if (L.contains(p))
L.remove(p);
CreatePath(maze, x, y-1, R, C, L);
return false;
}
else {
return false;
}
}
}
}