迷宫问题的DFS和BFS解法

迷宫问题的DFS和BFS解法

​ 写在前面:通过迷宫问题来熟悉dfs和bfs解法,加深对于这两种搜索方式的理解与运用

DFS算法

注:DFS可以求第一条路径,也可以求最短路径

算法过程

dfs(顶点V)
{
       标记顶点V以遍历;
       for(对于每一个邻接V且未被标记的顶点u);
       dfs(u);
}
Map = [[1 for i in range(100)] for j in range(100)]#迷宫数组,0表示可以通行,1表示不可通行
vis = [[0 for i in range(100)] for j in range(100)]#访问数组, 0表示未访问,1表示访问过
Min = 1000

def dfs(x, y, step):
    global Min,m,n
    if( x == m-1 and y == n-1):
        Min = min(step, Min)
##        if (step < Min):
##            Min = step
        return #用到了回溯
	#下面这四个步骤在bfs的算法中用一个for循环合并了
    #向右
    if (Map[x + 1][y] == 0 and vis[x + 1][y] == 0):
        vis[x +1][y] = 1
        dfs(x+1, y, step+1)
        vis[x+1][y] = 0
    #向下
    if(Map[x][y + 1] == 0 and vis[x][y + 1] == 0):
        vis[x][y + 1] = 1
        dfs(x, y+1, step+1)
        vis[x][y+1] = 0
    #向左
    if(Map[x - 1][y] == 0 and vis[x - 1][y] == 0):
        vis[x - 1][y] = 1
        dfs(x-1, y, step+1)
        vis[x - 1][y] = 0
    #向上
    if(Map[x][y - 1] == 0 and vis[x][y - 1] == 0):
        vis[x][y -1] = 1
        dfs(x, y-1, step+1)
        vis[x][y-1] = 0
    return Min
if __name__ == '__main__':
    m, n = map(int, input().split())
    for i in range(m):
        L = list(map(int, input().split(' ')))
        for j in range(n):
            Map[i][j] = L[j]
    vis[0][0] = 1
    print(dfs(0, 0, 0))

BFS算法过程

注:BFS算法找到的第一条路径是最短的路径

1、将起点入队列

2、队首节点可以到达的入队,如果没有可以到达的点,将队首出队

重复步骤2,直到达到目标位置,或者队列为空

maze =[[0, 0, 0, 0, 0, 0],
     [0, 1, 1, 0, 1, 0],
     [0, 1, 1, 1, 1, 0],
     [0, 1, 1, 0, 1, 0],
     [0, 1, 0, 1, 1, 0],
     [0, 1, 1, 1, 1, 0],
     [0, 0, 0, 0, 0, 0]]
#迷宫数组,1表示可以通行,0表示不可通行
r = []
#用数组来表示队列
vis = [[False for _ in range(len(maze[0]))] for _ in range(len(maze))]
#访问数组,用于辅助宽搜的过程记录
vis[1][1] = True
#从[1,1]这个点开始出发
flx, fly = map(int, input().split())
#起点和终点
start = [1, 1, 0]
#起始的数据,[x, y, step(步数)]
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
r.append(start)
while(r is not None):
    if r[0][0] == flx and r[0][1] == fly:
    #当走到终点时,输出步数
        print(r[0][2])
        break
    for i in range(4):
        tx = r[0][0] + dx[i]
        ty = r[0][1] + dy[i]
        if vis[tx][ty] == False and maze[tx][ty] == 1:
            vis[tx][ty] = True
            S = [tx, ty, r[0][2]+1]
            #入队列
            r.append(S)
    r.pop(0)
    #出队列

具体的实例

运用DFS解题的例子

题目

X 星球的一处迷宫游乐场建在某个小山坡上。它是由10×10 相互连通的小房间组成的。

房间的地板上写着一个很大的字母。我们假设玩家是面朝上坡的方向站立,则:

  • L 表示走到左边的房间,
  • R 表示走到右边的房间,
  • U 表示走到上坡方向的房间,
  • D 表示走到下坡方向的房间。

X 星球的居民有点懒,不愿意费力思考。他们更喜欢玩运气类的游戏。这个游戏也是如此!

开始的时候,直升机把 100100 名玩家放入一个个小房间内。玩家一定要按照地上的字母移动。

迷宫地图如下:

UDDLUULRUL
UURLLLRRRU
RRUURLDLRD
RUDDDDUUUU
URUDLLRRUU
DURLRLDLRL
ULLURLLRDU
RDLULLRDDD
UUDDUDUDLL
ULRDLUURRR

请你计算一下,最后,有多少玩家会走出迷宫,而不是在里边兜圈子?

代码

L = ['' for i in range(10)]
L[0] = "UDDLUULRUL"
L[1] = "UURLLLRRRU"
L[2] = "RRUURLDLRD"
L[3] = "RUDDDDUUUU"
L[4] = "URUDLLRRUU"
L[5] = "DURLRLDLRL"
L[6] = "ULLURLLRDU"
L[7] = "RDLULLRDDD"
L[8] = "UUDDUDUDLL"
L[9] = "ULRDLUURRR"
for i in range(10):
    for j in range(10):
        print(L[i][j],end='')
    print()
# print (L)
visited = [[0 for i in range(11)] for i in range(11)]
for i in range(11):
    for j in range(11):
        print(visited[i][j],end='')
    print()
print(L[2][4])
count = 0
def dfs(x, y):
    global count
    #这里使用了全局变量,可以把每个dfs的结果加在一起
    if (visited[x][y] == 1):
        return
    if (x < 0 or y < 0 or x >= 10 or y >= 10):
        count += 1
        return
    if (L[x][y] == "L"):
        visited[x][y] = 1
        dfs(x, y - 1)
        visited[x][y] = 0
    elif (L[x][y] == "R"):
        visited[x][y] = 1
        dfs(x, y + 1)
        visited[x][y] = 0
    elif (L[x][y] == "U"):
        visited[x][y] = 1
        dfs(x - 1, y )
        visited[x][y] = 0
    else:
        visited[x][y] = 1
        dfs(x + 1, y)
        visited[x][y] = 0

def test():
    for i in range(10):
        for j in range(10):
            dfs(i, j)

if __name__ == "__main__":
    test()
    print(count)

运用BFS解题的例子

题目:2019年真题
请添加图片描述

题目解答的代码

maze = [[1 for _ in range(55)] for _ in range(35)]
vis = [[False for _ in range(55)] for _ in range(35)]
way = [[0 for _ in range(50)] for _ in range(30)]
dx = [1, 0, 0, -1]
dy = [0, -1, 1, 0]
#dx,dy这两个的数组的设置有点奇怪,目前还没有理解透,有理解的大佬可以告知下
dir =['D', 'L', 'R', 'U']
r = []
file = open('maze.txt','r')
m, n = map(int,file.readline().split(' '))
#print(m, n)
for i in range(1,m+1):
    line = file.readline()
    #print(line)
    for j in range(1,n+1):
        maze[i][j] = int(line[j-1])
#输出生成的迷宫
##for i in range(m):
##    for j in range(n):
##        print(maze[i][j],end = '')
##    print('\n')
start = [1, 1, '']
#这里的第三个元素很灵活,可以是步数,也可以是这个题DULR这种方向
vis[1][1] = True
r.append(start)
while(r is not None):
    if (r[0][0] == 30 and r[0][1] == 50):
        print(r[0][2])
        break
    for i in range(4):
        tx = r[0][0] + dx[i]
        ty = r[0][1] + dy[i]
        if(vis[tx][ty] == False and maze[tx][ty] == 0):
            vis[tx][ty] = True
            S = [tx, ty, r[0][2]+dir[i]]
            r.append(S)
    r.pop(0)

maze.txt的数据

30 50
01010101001011001001010110010110100100001000101010
00001000100000101010010000100000001001100110100101
01111011010010001000001101001011100011000000010000
01000000001010100011010000101000001010101011001011
00011111000000101000010010100010100000101100000000
11001000110101000010101100011010011010101011110111
00011011010101001001001010000001000101001110000000
10100000101000100110101010111110011000010000111010
00111000001010100001100010000001000101001100001001
11000110100001110010001001010101010101010001101000
00010000100100000101001010101110100010101010000101
11100100101001001000010000010101010100100100010100
00000010000000101011001111010001100000101010100011
10101010011100001000011000010110011110110100001000
10101010100001101010100101000010100000111011101001
10000000101100010000101100101101001011100000000100
10101001000000010100100001000100000100011110101001
00101001010101101001010100011010101101110000110101
11001010000100001100000010100101000001000111000010
00001000110000110101101000000100101001001000011101
10100101000101000000001110110010110101101010100001
00101000010000110101010000100010001001000100010101
10100001000110010001000010101001010101011111010010
00000100101000000110010100101001000001000000000010
11010000001001110111001001000011101001011011101000
00000110100010001000100000001000011101000000110011
10101000101000100010001111100010101001010000001000
10000010100101001010110000000100101010001011101000
00111100001000010000000110111000000001000000001011
10000001100111010111010001000110111010101101111000
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值