用Java实现迷宫求解,基本实现就是DFS搜索,可以实现最短路径。 Point 是一个java类,主要属性石x,y,实现对坐标的抽象。
public final class Demo
{
private static int dirx[]={0,1,0,-1};
private static int diry[]={1,0,-1,0};
private int[][] flag;
private Point[][] record;
//保存路径的栈
private Stack<Point> stack = new Stack<Point>();
public Demo()
{
}
/*
功能:从一个迷宫走出的最短路徑
输入:
一个N*M的数组,int[][] maze迷宫图作为输入,如
{0, 1, 0, 0, 0},
{0, 1, 0, 1, 0},
{0, 0, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 1, 0}};
输出:从左上角到右下角的最短路线:(0, 0)(1, 0)(2, 0)(2, 1)(2, 2)(2, 3)(2, 4)(3, 4)(4, 4)
*/
public Stack<Point> go(int[][] maze)
{
Point out = new Point(maze.length - 1, maze[0].length - 1); //出口
Point in = new Point(0, 0); //入口
//search
Queue<Point> queue= new LinkedList<Point>();
queue.offer(in);
Point current_point = new Point();
Point new_point;
flag = new int[maze.length][maze[0].length]; //record 走过没有
record = new Point[maze.length][maze[0].length]; //record 前驱节点
for(int i = 0 ; i < flag.length ; i++){
for(int j = 0 ; j < flag[0].length;j++){
flag[i][j] = 0;
}
}
flag[in.getX()][in.getY()] = 1;
int x,y;
while(!queue.isEmpty()){
current_point = queue.peek();
queue.poll();
if(current_point.getX() == out.getX() && current_point.getY() == out.getY()){
break;
}
for(int i=0;i<4;i++){ //move to 4 direction
x = current_point.getX() + dirx[i];
y = current_point.getY() + diry[i];
if(x >= in.getX() && x <= out.getX() && y >= in.getY() && y <= out.getY() && maze[x][y] != 1 && flag[x][y] == 0)// judge whether is accessible or back or out of board //防止坐标溢出,同时判断是否碰到墙壁或者走回原路
{
new_point = new Point(x,y);
queue.add(new_point);
flag[new_point.getX()][new_point.getY()] = 1;//record
record[new_point.getX()][new_point.getY()] = current_point;
}
}
}
//path
if(flag[current_point.getX()][current_point.getY()] != 0){
Stack<Point> path = new Stack<Point>();
path.push(out);
int i = record[out.getX()][out.getY()].getX();
int j = record[out.getX()][out.getY()].getY();
while(i != in.getX() || j != in.getY()){
path.push(new Point(i,j));
int m = record[i][j].getX();
int n = record[i][j].getY();
i=m;j=n;
}
path.push(new Point(0,0));
Collections.reverse(path);
return path;
}
else{
return null;
}
}
}