您的位置:首页 > 其它

(深度优先搜索dfs经典例题)走迷宫

2019-03-20 01:12 274 查看

(深度优先搜索dfs经典例题)走迷宫

描述

这种dfs太经典啦,就不多描述了下面用一对输入输出数据直接描述问题

5 6
....S*
.***..
.*..*.
*.***.
.T....
第一行:输入行数和列数
墙壁:*(星号)
路:.(英文句号)
开始标记:S
结束标记:T

输出图形:

....S*
.***LL
.*..*L
*.***L
.TLLLL

用L标记所走的路径

思想

这道题简直是dfs的最经典题目
思想很简单,每一步有四个方向可以选择,上、左、下、右,可以走就继续,不行就回退。

c++ code

#include<iostream>
#include<string>
using namespace std;

//数据部分
string maze[101];																													//迷宫
int vis[101][101];																													//访问数组
int m, n;																																//m行n列
int turn[4][2] = { {-1, 0}, {0, -1}, {1, 0}, {0, 1} };																		//转向数组 上、左、下、右

//函数部分
bool in(int x, int y) {																												//判断坐标是否在地图内
if (0 <= x && x < m && 0 <= y && y < n)
return true;
else
return false;
}
bool dfs(int x, int y){																												//深度优先搜索
if (maze[x][y] == 'T') return true;																							//到达终点直接返回true
if(maze[x][y] != 'S')
maze[x][y] = 'L';																											//标记路径
vis[x][y] = 1;																													//访问位置1

int tx = 0;
int ty = 0;
for (int i = 0; i < 4; i++) {
tx = x + turn[i][0];
ty = y + turn[i][1];
if (in(tx, ty) && maze[tx][ty] != '*' && !vis[tx][ty]) {																//在地图内 且 没有撞墙 且 没有访问此位
if(dfs(tx, ty))																												//继续走下去
return true;
}
}

maze[x][y] = '.';																													//如果四个方向都不行就将之前做过的标记清除 之后返回false
vis[x][y] = 0;
return false;
}

int main(void) {
cin >> m >> n;																													//迷宫的规模
for (int i = 0; i < m; i++)
cin >> maze[i];																												//输入迷宫

int x = 0;
int y = 0;
for(int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (maze[i][j] == 'S') {
x = i;
y = j;
}
}

cout << endl;

if (dfs(x, y)) {
for (int i = 0; i < n; i++)
cout << maze[i] << endl;
}
else
cout << "地图没有出口!" << endl;

cout << endl;
system("pause");
return 0;
}

/*
测试数据:
5 6
![....S*
.***..
.*..*.
*.***.
.T....
*/

python code

maze = []                                           # 地图
m = 0                                               # m行
n = 0                                               # n列
turn = [[-1, 0], [0, -1], [1, 0], [0, 1]]           # 方向数组

def In(x, y):                                       # 判断是否在地图内
if 0 <= x < m and 0 <= y < n:
return True
else:
return False
def dfs(x, y):                                      # 行走数组
if maze[x][y] == 'T': return True
print(x, y)
vis[x][y] = 1
if maze[x][y] != 'S': maze[x][y] = 'L'
for i in range(4):
tx = x + turn[i][0]
ty = y + turn[i][1]
if not vis[tx][ty] and maze[tx][ty] != '*' and In(tx, ty):
if dfs(tx, ty): return True
vis[x][y] = 0
maze[x][y] = '.'
return False

m, n = [int(input()) for i in range(2)]
vis = [[0 for i in range(n)] for j in range(m)]     # vis数组
for i in range(m):
maze.append(list(input()))
for i in range(m):
for j in range(n):
if maze[i][j] == 'S':x = i; y = j
if dfs(x, y):
for temp in maze:
print(' '.join(temp))
else:
print('迷宫没有出路!')

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