迷宫搜索问题最短路_使用BFS(广度优先搜索)解迷宫类问题

在这学期的Computing for Finance in Python上有这么一道算法题:

8bfff8ca8186bee3ff9c6ef8155bc5e3.png

05b851635c2e667a35e0c317a230edc0.png

f9c4e46fa3ad2e553666ee7b363488d5.png

简单来说,输入一个list of lists,对于每一个位置,用0表示可经过的方块,用2表示金币,用1表示没有办法经过的blocks。要在获取到所有金币的情况下,找出从B(0,0) A的最短路径。如果这个路径不存在,则返回-1.

Solutions 1:

(感谢同专业的Vera Chim提供的代码,我的代码只能通过一半的testcase,匿了。同时,我将注释尽可能详细地写在代码块中)

1

from itertools import permutations

2

 

3

def bfs(maze, coin, i, dd): # coin is the list of coordinate tuples of coins, i is its index

4

    queue = [] # 用来记录备选坐标,便于下一次基于这个坐标再向四个方向进行遍历

5

    queue.append((coin[i], 0))

6

    records = set() # 用来记录所有访问过的坐标

7

    golds = 0 # 累计得到的金币

8

    r = len(maze)

9

    c = len(maze[0])

10

    while len(queue) > 0 and golds < len(coin): # 要么走完所有可能路径,要么已搜集到所有金币,停止循环

11

        (x, y), step = queue[0]

12

        queue.remove(((x, y), step))

13

        if (x, y) in coin and (x, y) not in records: # 如果当前坐标上有金币,且之前没走过

14

            dd[i][coin.index((x, y))] = step # 对应dd的位置赋值为 step

15

            golds += 1

16

        records.add((x, y))

17

        if maze[x][y] != 1: # 不会撞墙

18

            if x+1 < r and (x+1, y) not in records and ((x+1, y), step+1) not in queue:

19

                queue.append(((x+ 1, y), step + 1)) # 向右走一步,不越界,之前没走过,相同step不走重

20

                

21

            if x-1 >= 0 and (x - 1, y) not in records and ((x - 1, y), step + 1) not in queue:

22

                queue.append(((x- 1, y), step + 1)) # 向左走一步,不越界,之前没走过,相同step不走重

23

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值