回溯的处理思想有点类似枚举搜索。通过枚举所有的解,找到满足期望的解。为了有规律地枚举所有可能的解,避免遗漏和重复,我们把问题求解的过程分为多个阶段。每个阶段,都会面对一个岔路口,我们先随意选一条路走,当发现这条路走不通的时候(不符合期望的解),就回退到上一个岔路口,另选一种走法继续走
摘自:https://blog.csdn.net/qq_40378034/article/details/102764545
解题思路:迷宫中,进入死胡同就往回走到上一个岔路口,选择另一条路,显然是一个回溯的过程
递归结束条件? 到达终点
回溯的条件?进入死胡同
判断能否继续前进的条件:坐标是否越界,坐标代表的方格是否为墙,坐标代表的方格是否被走过
代码实现
package com.算法.part01分治回溯;/*
* 作用:回溯之迷宫问题
*
*@author hby_gd@163.com
*@date 21/7/2020 上午12:32
*/
import java.util.ArrayDeque;
public class Maze {
//默认迷宫
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 originX = 1;
private static int originY = 0;
//终点
private static int destinationX =7;
private static int destinationY =8;
//标记迷宫中路的状态
private static boolean[][] isVisited = new boolean[9][9];
//存储走过的路径
private static ArrayDeque<String> stack = new ArrayDeque<>();
//储存不同方向,xy坐标变化 顺序,上、右、下、左
private static int[][] direction = {{-1,0},{0,1},{1,0},{0,-1}};
public static void main(String[] args) {
//起点默认走过
isVisited[originX][originY] = true;
processMaze(originX,originY);
System.out.println(stack.toString());
}
private static void processMaze(int x, int y) {
//当前坐标的字符串形式
String point = new String("("+x+","+y+")");
if(x==destinationX&&y==destinationY){
stack.push(point);
return;
}
//判断位移方向
for (int i = 0; i < 4; i++) {
if(check(x,y,direction[i])){
stack.push(point);
x = x+direction[i][0];
y = y+direction[i][1];
isVisited[x][y] = true;
processMaze(x,y);
}
}
//没有位移,回溯至上一位置
if(!stack.element().equals(point)){
String s = stack.pop();
processMaze(Integer.parseInt(s.charAt(1)+""),Integer.parseInt(s.charAt(3)+""));
}
}
private static boolean check(int x, int y, int[] ints) {
int newX = x+ints[0];
int newY = y+ints[1];
//越界、墙、走过
if(newX<0||newX>8||newY<0||newY>8||maze[newX][newY]==1||isVisited[newX][newY]){
return false;
}
return true;
}
}