递归解迷宫加强版本 得到所有的走出迷宫的路 直接代码
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class MazeRecursion {
static int maze[][]={
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,0,0,1},
{1,0,1,1,1,0,1,1,0,1},
{1,1,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
static int[][]directions={
{-1,0},{0,1},{1,0},{0,-1}
};
static class Step{
int x,y;
public Step(int x, int y) {
super();
this.x = x;
this.y = y;
}
Step add(int[] xy){
Step stepNew=new Step(x, y);
stepNew.x+=xy[0];
stepNew.y+=xy[1];
return stepNew;
}
Step copy(){
Step stepNew=new Step(x,y);
return stepNew;
}
@Override
public String toString() {
return x+","+y;
}
@Override
public boolean equals(Object obj) {
return obj!=null&&obj instanceof Step && x==((Step)obj).x&&y==((Step)obj).y;
}
}
static Step start=new Step(1, 1);
static Step end=new Step(8,8);
public static void main(String[] args){
int mazeCopy[][]=new int[maze.length][maze[0].length];
for(int i=0;i<mazeCopy.length;i++){
for(int j=0;j<mazeCopy[0].length;j++){
mazeCopy[i][j]=maze[i][j];
}
}
Stack<Step> stack =new Stack<Step>();
stack.add(start);
maze[start.x][start.y]=-1;
List<Stack<Step>> list=new ArrayList<Stack<Step>>();
int path = getPath(list,stack, maze, start, end);
System.out.println(path);
// while(!stack.isEmpty()){
// Step step=stack.pop();
// System.out.println(step);
// }
System.out.println(list.size());
for (Stack<Step> stack2 : list) {
for (Step step : stack2) {
System.out.println(step);
}
System.out.println("-----------------------");
}
}
private static int getPath(List<Stack<Step>> list,Stack<Step> stack,int [][] maze,Step stepNow,Step stepEnd){
if(stepNow.equals(stepEnd)){
Stack<Step> stackAnswer=new Stack<Step>();
for(int i=0;i<stack.size();i++){
stackAnswer.add(stack.get(i));
}
list.add(stackAnswer);
return 0;
}
for(int i=0;i<directions.length;i++){
Step stepNext=stepNow.add(directions[i]);
// System.out.println(stepNext);
if(maze[stepNext.x][stepNext.y]==0){
stack.push(stepNext);
maze[stepNext.x][stepNext.y]=-1;
int result=getPath(list,stack, maze, stepNext, stepEnd);
if(result!=1){
stack.pop();
maze[stepNext.x][stepNext.y]=0;
}else{
return 1;
}
}
}
return 0;
}
}