深度优先搜索求解迷宫问题

1.问题描述

  定义一个二维数组:

  int  maze[5][5] = {

        0,1, 0, 0, 0,

        0,1, 0, 1, 0,

        0,0, 0, 0, 0,

        0,1, 1, 1, 0,

        0,0, 0, 1, 0,

};

  它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的路线。

2.代码

  

package cn.edu.hit;

import java.util.Stack;

/**
 * 用深度优先算法求解迷宫问题
 * @author admin
 *
 */
public class Maze {
 //当然也可以用同样大的矩阵来标记没个走过的点,避免重复走回原来的路
	private int m,n;//m和n是用来记录上一步的坐标,不能让下一步又走回去,这样永远走不完
	public static Stack<int[]> s;
	public static void main(String[] args) {
		//声明迷宫,1表示不通,0表示通
		int[][] maze = {{0,1,0,0,0},{0,1,0,1,0},{1,1,1,1,1},{0,1,1,1,0},{0,0,0,1,0}};
		s = new Stack<int[]>();//用来存储路线
		Maze m = new Maze();
		if(m.out(0, 0, maze)){
			for (int[] is : s) {
				System.out.println(is[0]+" "+is[1]);
			}
			System.out.println("走出去了");
		}else{
			System.out.println("走不出去");
		}
	}

	public boolean out(int x,int y,int[][] array){
		m = x;
		n = y;
		if(x==4 && y==4){
			return true;
		}
		int[] a = new int[2];
		//向下走
		if(y+1<5 && array[x][y+1] == 0 && x != m && y+1 != n){
			a[0] = x;
			a[1] = y+1;
			if (out(x, y+1, array)) {
				s.push(a);
				return true;
			}else{
				s.pop();
				array[x][y+1] = 1;//弹出去说明此路不通,直接标记为1
			}
		}
		//向右走
		if(x+1<5 && array[x+1][y] == 0 && x+1 != m && y != n){
			a[0] = x+1;
			a[1] = y;
			if (out(x+1, y, array)) {
				s.push(a);
				return true;
			}else{
				s.pop();
				array[x+1][y] = 1;//弹出去说明此路不通,直接标记为1
			}
		}
		if(y-1>-1 && array[x][y-1] == 0 && x != m && y-1 != n){
			a[0] = x;
			a[1] = y-1;
			if (out(x, y-1, array)) {
				s.push(a);
				return true;
			}else{
				s.pop();
				array[x][y-1] = 1;//弹出去说明此路不通,直接标记为1
			}
		}
		if(x-1>-1 && array[x-1][y] == 0 && x-1 != m && y != n){
			a[0] = x-1;
			a[1] = y;
			if (out(x-1, y, array)) {
				s.push(a);
				return true;
			}else{
				s.pop();
				array[x-1][y] = 1;//弹出去说明此路不通,直接标记为1
			}
		} 
		return false;
	}
}

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/lzc534650799/article/details/72426913
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞