深度优先
不撞南墙不回头
思路分析
代码再现
/**
* 深度优先--不撞南墙不回头
*
* 递归调用
*
* @author Bamboo
*
*/
public class Dfs {
//地图的大小
int n,m;
//定义地图,如果值为0表示节点无障碍,值为1表示节点有障碍
int[][] data = null;
//标记已经走过的节点
boolean[][] marked = null;
//开启调试
boolean debug = true;
/**
* 0,1 表示往前走
* 0,-1 表示往后走
* 1,0 表示往上走
* -1,0 表示往下走
*/
int[][] direction = {{0,1},{0,-1},{1,0},{-1,0}};
//最短距离
int minDepth = Integer.MAX_VALUE;
//可能的最短距离
List<Stack> possibilityPath = new ArrayList<>();
//目标位置
point dest;
public Dfs() {
}
/**
5 4
0 0 1 0
0 0 0 0
0 1 0 1
0 0 0 0
0 0 0 1
3 2
* @param x
* @param y
* @param depth
* @param temp 标记走过的路径位置
*/
public void dfsSearch(int x,int y,int depth,Stack<String> stack) {
//记录已经走过的位置
stack.push(x+","+y);
if(x==dest.dx && y ==dest.dy) {
if( debug ) {
System.out.println("目标被找到...当前深度="+depth);
for(int i=0;i<stack.size();i++) {
System.out.print(stack.elementAt(i)+" ");
}
System.out.println();
}
if(depth <= minDepth) {
//记录最小深度
if(depth < minDepth) {
minDepth = depth;
possibilityPath.clear();
}
possibilityPath.add((Stack) stack.clone());
}
}
//开始从四个方向深度寻找下一个点
for(int i=0; i<direction.length; i++) {
int nextx = direction[i][0]+x;
int nexty = direction[i][1]+y;
//超出边界,位置无效,退出
if(nextx<0 || nextx>=m || nexty<0 || nexty>=n)
continue;
//该位置存在障碍物不能走的,需要绕路
if( data[nextx][nexty]==1 )
continue;
//当前位置已经走过,不要再走了
if( marked[nextx][nexty]==true )
continue;
//标记已经走过
marked[nextx][nexty]=true;
//寻找下一个节点
dfsSearch(nextx, nexty, ++depth,stack);
//回溯 深度减少
--depth;
//回溯,标记为未走过
marked[nextx][nexty]=false;
//回溯 ,取消标记
stack.pop();
}
}
public static void main(String[] args) throws IOException {
Dfs dfs = new Dfs();
//关闭调试
dfs.debug =false;
try(Scanner dis = new Scanner(System.in)){
dfs.m = dis.nextInt();
dfs.n = dis.nextInt();
dfs.data = new int[dfs.m][dfs.n];
dfs.marked = new boolean[dfs.m][dfs.n];
for(int i=0; i<dfs.m ; i++ ) {
for(int j=0; j<dfs.n; j++) {
dfs.data[i][j] = dis.nextInt();
}
}
dfs.dest = new point(dis.nextInt(),dis.nextInt());
}
dfs.dfsSearch(0, 0, 0,new Stack());
System.out.println("最小深度:"+dfs.minDepth);
for(int i=0;i<dfs.possibilityPath.size();i++) {
System.out.println("可能的方案"+(i+1)+":"+dfs.possibilityPath.get(i));
}
}
static class point {
int dx;
int dy;
public point(int dx,int dy) {
this.dx = dx;
this.dy = dy;
}
}
}