代码:
import collections
def bfs(G,s):
P,Q={s:None},collections.deque([s])
while Q:
u=Q.popleft()
for v in G[u]:
if v in P:continue
P[v]=u
Q.append(v)
return P
if __name__=="__main__":
a, b, c, d, e, f, g, h, i= range(9)
N = [
{b, c, d}, # a
{a, d}, # b
{a,d}, # c
{a,b,c}, # d
{g,f}, # e
{e,g}, # f
{e,f}, # g
{i}, # h
{h} #i
]
G=[{b,c,d,e,f},#a
{c,e},#b
{d},#c
{e},#d
{f},#e
{c,g,h},#f
{f,h},#g
{f,g}#h
]
p=bfs(G,0)
运行:
>>> p
{0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 5, 7: 5}
寻找从a到u的路径的话,只需要在返回的队列中“往回倒”就好了。
>>> u=6
>>> path =[u]
>>> while p[u] is not None:
path.append(p[u])
u=p[u]
>>> path.reverse()
>>>
>>> path
[0, 5, 6]