Java小案例-(逃离迷宫)
一,迷宫需求描述:
1,用户输入迷宫图(限制方形):字母1位墙,0为通,e为出口,m为入口,*为已访问的位置,用外围1围住迷宫
2,运行轨迹右,左,下,上
3,判断该迷宫是否能从入口走到出口,并将搜索过程输出
二,迷宫实现:
1,迷宫元素类MazeCell:
package smalldemo.maze; class MazeCell { public int x,y; public MazeCell(){ } public MazeCell(int x,int y){ this.x=x; this.y=y; } public boolean equals(MazeCell cell){ return x==cell.x && y==cell.y; }}
2,迷宫搜索类MazeUtils:
package smalldemo.maze;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import java.util.Stack;class MazeUtils { private int rows,columns; private MazeCell currentCell,exitCell=new MazeCell(),entryCell=new MazeCell(); private final char wall='1',passage='0',visited='*',entryMarker='m',exitMarker='e'; private char[][] stores; private StackmazePath=new Stack (); MazeUtils(){ int row=0,column=0; InputStreamReader in=new InputStreamReader(System.in); BufferedReader buf=new BufferedReader(in); Stack mazeRows=new Stack (); System.out.println("Enter a rectangular maze using the following"+ "characters\nm -entry\ne -exit\n1 - wall \n0 - passage\n"+"Enter one line at one time:" + "end with Ctrl- D:"); try { String str=buf.readLine(); while(str !=null) { row += 1; columns = str.length(); str = "1" + str + "1"; mazeRows.push(str); if (str.indexOf(entryMarker) != -1) { entryCell.x = row; entryCell.y = str.indexOf(entryMarker); } if (str.indexOf(exitMarker) != -1) { exitCell.x = row; exitCell.y = str.indexOf(exitMarker); } str = buf.readLine(); } } catch (IOException e) { e.printStackTrace(); } rows=row; stores=new char[rows+2][]; stores[0]=new char[columns+2]; for(;!mazeRows.empty();row --){ stores[row]=mazeRows.pop().toCharArray(); } stores[rows+1]=new char[columns+2]; for(int i=0;i
3,结果是:
Enter a rectangular maze using the followingcharactersm -entrye -exit1 - wall 0 - passageEnter one line at one time:end with Ctrl- D:1101000e00m1^D1111111110111000e1100m111111111110111000e1100*111111111110111000e110**111111111110111000e11***111111111110111*00e11***111111111110111**0e11***111111111110111***e11***11Success!Process finished with exit code 0