一个迷宫,他有一个入口和一个出口,试寻找一条从入口到出口的路径。
import java.util.Stack;
public class Maze {
//保存迷宫
private int[][] maze;
//入口与出口
private Location in;
private Location out;
//保存路径
private Stack<Location> stack;
//初始化
public Maze(int[][] maze, int x1,int y1,int x2,int y2) {
this.maze = maze;
this.in = new Location(x1,y1);
this.out = new Location(x2,y2);
stack = new Stack<Location>();
}
//开始游荡
public Stack<Location> getWay(){
stack.push(in);
while (!stack.isEmpty()){
if(stack.peek().x==out.x&&stack.peek().y==out.y){
break;
}
//向右
if(stack.peek().x+1<maze[0].length&&maze[stack.peek().x+1][stack.peek().y]==1){
goRight(new Location(stack.peek().x+1,stack.peek().y));
continue;
}
//向下
if(stack.peek().y+1<maze.length&&maze[stack.peek().x][stack.peek().y+1]==1){
goDown(new Location(stack.peek().x,stack.peek().y+1));
continue;
}
//向上
if(stack.peek().y-1>=0&&maze[stack.peek().x][stack.peek().y-1]==1){
goUp(new Location(stack.peek().x,stack.peek().y-1));
continue;
}
//向左
if(stack.peek().x-1>=0&&maze[stack.peek().x-1][stack.peek().y]==1){
goLeft(new Location(stack.peek().x-1,stack.peek().y));
continue;
}
//三处走不通则回退
Location pop = stack.pop();
}
if(stack.isEmpty()){
return null;
}
return stack;
}
//向下
private void goDown(Location down) {
stack.push(down);
maze[down.x][down.y]=0;
}
//向上
private void goUp(Location up) {
stack.push(up);
maze[up.x][up.y]=0;
}
//向左
private void goLeft(Location left) {
stack.push(left);
maze[left.x][left.y]=0;
}
//向右
private void goRight(Location right) {
stack.push(right);
maze[right.x][right.y]=0;
}
public class Location{
private int x;
private int y;
public Location(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "location{" +
"x=" + x +
", y=" + y +
'}';
}
}
}
测试