【回溯法】迷宫问题
问题描述
从一个迷宫地图入口处进入,迷宫中有许多墙,使得大多数的路径都被挡住而无法行进。可以通过遍历所有可能到出口的路径来到达出口。当走错路时要返回上一个位置,看上一个位置是否有其他方向的路可以走,依次循环进行吗,直到找到出口位置直到找到出口。
在迷宫中要遵循以下原则:
1、一次步进只能走一格
2、遇到墙后,退后直到找到其他路径
3、走过的路径记录下来,表示已经走过了
示例
输入描述:
迷宫边长
入口坐标
出口坐标
输出描述:
迷宫路径
输入:
9
1 0
7 8
输出:
(1,0) (1,1) (2,1) (3,1) (3,2) (4,2) (5,2) (5,3) (5,4) (5,5) (4,5) (4,6) (4,7) (5,7) (6,7) (7,7) (7,8)
(1,0) (1,1) (2,1) (3,1) (3,2) (4,2) (5,2) (5,3) (5,4) (5,5) (6,5) (6,6) (6,7) (7,7) (7,8)
解题思路
回溯法,从入口开始,遍历各个路径,遇到墙就回溯
代码
//迷宫问题——回溯法
public class Maze {
static int n;
static int startX,startY,endX,endY;
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}
};
static int [][]direction = {{-1,0},{0,1},{1,0},{0,-1}};
static int [][]visited;
static LinkedList<String> path = new LinkedList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
startX = sc.nextInt();
startY = sc.nextInt();
endX = sc.nextInt();
endY = sc.nextInt();
visited = new int[n][n];
dfs(startX,startY);
}
public static void dfs(int x,int y){
path.push("(" + x + "," + y + ")");
visited[x][y] = 1;
if(x == endX && y == endY){
String paths = "";
String temp = "";
for(String str: path){
temp = paths;
paths = str + " " + temp ;
}
System.out.println(paths);
}
else{
for(int i = 0;i < direction.length;++i){
int newX = x+direction[i][0], newY = y+direction[i][1];
if(newX>=0 && newX<n && newY>=0 && newY<n && visited[newX][newY]!=1){ //没出界并且没被访问过
if (maze[newX][newY] != 1)
dfs(x+direction[i][0],y+direction[i][1]);
}
}
}
path.pop();
visited[x][y]=0;
}
}