您的位置:首页 > 其它

深度优先搜索例1--走迷宫问题

2017-05-25 17:02 441 查看
题目请见:http://blog.csdn.net/nanyangtangheguotan/article/details/71248430

/**
* 深度优先搜索解决走迷宫问题
* @author 王孙悟空
*/
public class Main {
/**
* 数组maze存放迷宫二维表
*/
static int maze[][] = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 1, 1, 1, 0, 1, 0 }, { 0, 0, 0, 0, 1, 0, 1, 0 },
{ 0, 1, 0, 0, 0, 0, 1, 0 }, { 0, 1, 0, 1, 1, 0, 1, 0 },
{ 0, 1, 0, 0, 0, 0, 1, 1 }, { 0, 1, 0, 0, 1, 0, 0, 0 },
{ 0, 1, 1, 1, 1, 1, 1, 0 } };
// 存放搜索的方向----右下左上
static int direct[] = { 0, 1, 0, -1, 0 };

public static void main(String[] args) {
maze[0][0]=-1;
dfs(0, 0);

}

// 走过的用-1标记
// 深度优先搜索固定格式循环加递归
static void dfs(int x, int y) {
for (int i = 0; i < direct.length - 1; i++) {
// 试探
x += direct[i];
y += direct[i + 1];
if (checked(x, y)) {
maze[x][y] = -1;
// 递归出口
if (x == maze.length - 1 && y == maze.length - 1) {
for (int j = 0; j < maze.length; j++) {
for (int j2 = 0; j2 < maze.length; j2++) {
if (maze[j][j2] == -1) {
System.out.print("("+(j + 1) + "," + (j2 + 1)+")");
}
}
}
return;
}
dfs(x, y);
maze[x][y]=0;//回溯
}
// 回溯
x -= direct[i];
y -= direct[i + 1];

}
}

// 检查是否可行
static boolean checked(int x, int y) {
// 判断超出迷宫范围
if (x < 0 || y < 0 || x >= maze.length || y >= maze.length) {
return false;
}
// 是墙或已走过
if (maze[x][y] == 1 || maze[x][y] == -1) {
return false;
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: