回溯
是一个类似枚举的搜索尝试过程,是在搜索尝试过程中寻找解决问题的解,当不满足时,就“回溯”返回,重新尝试。
是一种选优搜索法。
从一条路往前走,能进则进,不能进则退,换一条路试试。
用于递归的返回段。
迷宫问题
public class Main{
private static int[][] maze{
{1,1,1,1,1,1,1,1,1},
{0,0,1,0,0,0,1,1,1},
{1,0,1,1,1,0,1,1,1},
{1,0,0,1,0,0,1,1,1},
{1,1,0,1,1,0,0,0,1},
{1,0,0,0,0,0,1,0,1},
{1,0,1,1,1,0,0,0,1},
{1,1,0,0,0,0,1,0,0},
{1,1,1,1,1,1,1,1,1}
};
//入口坐标
private static int enterX=1;
private static int enterY=0;
//出口坐标
private static int exitX=7;
private static int exitY=8;
//记录每一个路径的访问状态,未访问:F
private static boolean[][] visited = new boolean[9][9];
//方向变换数组
private static int[][] direction={{-1,0},{0,1},{1,0},{0,-1}};
//定义一个栈 存储经过的路径
private static LinkedList<String> stack = new LinkedList<>();
public static void main(String[] args){
go(exitX,exitY);
}
//返回的意思是,从(x,y)向下递归是否能够走通。
private static boolean go(int x,int y){
stack.push("("+x+","+y+")");
visited[x][y]=ture;
if(x==exitX && y==exitY){
return turn;
}
for(int i=0;i<direction.length;i++){
int newX=x+direction[i][0];
int newY=y+direction[i][1];
if(isInArea(newX,newY)&&isRoad(newX,newY)&&!visited[newX][newY]){
//如果以新的坐标(newX,newY)向下寻求路径能走通则表示当前x,y向下能走通。
if(go(newX,newY)){
return turn;
}
}
}
stack.pop();
return false;
}
private static boolean isInArea(int x,int y){
return x>=0 && x<9 && y>=0&&y<9;
}
private static boolean isRoad(int x,int y){
return maze[x][y]==0;
}
}