在这学期的Computing for Finance in Python上有这么一道算法题:
简单来说,输入一个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