您的位置:首页 > 其它

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

2017-05-17 19:42 204 查看

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: