迷宫求解

求解迷宫的算法思想可以描述为: 初始化,将起点加入堆栈; while(堆栈不空){ 取出栈顶位置作为当前位置; 如果 当前位置是终点, 则 使用堆栈记录的路径标记从起点至终点的路径; 否则{ 按照向下、右、上、左的顺序将当前位置下一个可以探索的位置入栈; //从堆栈取出的探索方向顺序则是左、上、右、下 如果 当前位置没四周均不可通 则 当前位置出栈; } }

 

 

private class Cell{
 int x = 0; //单元所在行
 int y = 0; //单元所在列
 boolean visited = false; //是否访问过
 char c = ' '; //是墙('1')、可通路('0')或起点到终点的路径('*')
 public Cell(int x, int y, char c, boolean visited){
 this.x = x; this.y = y;
 this.c = c; this.visited = visited; 
}
 } 
public void mazeExit(char[][] maze,int sx,int sy, int ex,int ey){
 Cell[][] cells = createMaze(maze); //创建化迷宫
 printMaze(cells); //打印迷宫
 Stack s = new StackSLinked(); //构造堆栈
 Cell startCell = cells[sx][sy]; //起点
 Cell endCell = cells[ex][ey]; //终点
 s.push(startCell); //起点入栈
 startCell.visited = true; //标记起点已被访问
 while (!s.isEmpty()){
 Cell current = (Cell)s.peek();
 if (current==endCell){ //路径找到
 while(!s.isEmpty()){
 Cell cell = (Cell)s.pop();//沿路返回将路径上的单元设为*
 cell.c = '*';
 //堆栈中与 cell 相邻的单元才是路径的组成部分,除此之外,
 //堆栈中还有记录下来但是未继续向下探索的单元,
//这些单元直接出栈
 while(!s.isEmpty()&&!isAdjoinCell((Cell)s.peek(),cell)) s.pop();
 }
 System.out.println("找到从起点到终点的路径。");
 printMaze(cells);
 return;
 } else { //如果当前位置不是终点
 int x = current.x;
 int y = current.y;
 int count = 0;
 if(isValidWayCell(cells[x+1][y])){ //向下
 s.push(cells[x+1][y]); cells[x+1][y].visited = true; count++;}
 if(isValidWayCell(cells[x][y+1])){ //向右
 s.push(cells[x][y+1]); cells[x][y+1].visited = true; count++;}
 if(isValidWayCell(cells[x-1][y])){ //向上
 s.push(cells[x-1][y]); cells[x-1][y].visited = true; count++;}
 if(isValidWayCell(cells[x][y-1])){ //向左
 s.push(cells[x][y-1]); cells[x][y-1].visited = true; count++;}
 if (count==0) s.pop();//如果是死点,出栈
 }//end of if
 }//end of while
 76
 System.out.println("没有从起点到终点的路径。");
 }

 private void printMaze(Cell[][] cells){
 for (int x=0;x<cells.length;x++){
 for (int y=0;y<cells[x].length;y++)
 System.out.print(cells[x][y].c);
 System.out.println();
 }
 }
 private boolean isAdjoinCell(Cell cell1, Cell cell2){
 if (cell1.x==cell2.x&&Math.abs(cell1.y-cell2.y)<2) return true;
 if (cell1.y==cell2.y&&Math.abs(cell1.x-cell2.x)<2) return true;
 return false;
 }
 private boolean isValidWayCell(Cell cell){
 return cell.c=='0'&&!cell.visited;
 }
 private Cell[][] createMaze(char[][] maze){
 Cell[][] cells = new Cell[maze.length][];
 for (int x=0;x<maze.length;x++){
 char[] row = maze[x];
 cells[x] = new Cell[row.length];
 for (int y=0; y<row.length;y++)
 cells[x][y] = new Cell(x,y,maze[x][y],false);
 }
 return cells;
 } 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值