深度优先搜索例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;
}
}
/**
* 深度优先搜索解决走迷宫问题
* @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;
}
}
相关文章推荐
- 用深度优先搜索解迷宫问题
- 用深度优先搜索解迷宫问题
- 求解:栈的应用 深度优先搜索:迷宫问题
- 迷宫问题的求解方式:应用深度优先和广度优先的搜索
- 用深度优先搜索解迷宫问题 By LYLtim
- 【面试题】迷宫问题-----深度优先搜索----栈
- 深度优先搜索——迷宫问题(华为oj)
- 写给妹妹的编程札记 4 - 搜索: 迷宫问题 - 深度优先搜索
- 深度优先搜索找迷宫的出路
- hdu 2181 哈密顿绕行世界问题,深度优先搜索求解
- HDU1269--迷宫城堡--深度优先搜索
- 写给妹妹的编程札记 5 - 搜索: 迷宫问题 - 广度优先搜索
- 广度优先搜索求解迷宫问题
- makefile 入门指南实例——深度优先迷宫搜索
- 深度优先搜索找迷宫的出路
- 广度优先搜索--POJ迷宫问题
- makefile 入门指南实例——深度优先迷宫搜索
- 深度优先搜索之部分和问题
- 【游戏编程】AI-迷宫寻路算法-深度优先搜索和广度优先搜索
- 搜索之深度优先【迷宫搜索】(判断是否n步恰好可以到达某点)