from collections import deque BIG = 1e10 class vertexColors: WHITE = 0 GRAY = 1 BLACK = 2 class vertex: color = vertexColors.WHITE distance = BIG pre = None def __init__(self,id): self.id = id def __repr__(self): return self.id a = vertex("a") b = vertex("b") c = vertex("c") d = vertex("d") e = vertex("e") f = vertex("f") graph = { a : [c], b : [c, e], c : [a, b, d, e], d : [c], e : [c, b], f : [] } wgraph = { a : [(c,1)], b : [(c,2), (e,2)], c : [(a,1), (b,2), (d,0), (e,6)], d : [(c,0)], e : [(c,6), (b,2)], f : [] } def bfs(g,s): for u in g.keys(): u.color = vertexColors.WHITE u.distance = BIG u.pre = None s.color = vertexColors.GRAY s.distance = 0 s.pre = None q = deque() q.append(s) while len(q) > 0: u = q.popleft() for v in g[u]: if v.color == vertexColors.WHITE: v.color = vertexColors.GRAY v.distance = u.distance + 1 v.pre = u q.append(v) u.color = vertexColors.BLACK def bfsw(g,s): for u in g.keys(): u.color = vertexColors.WHITE u.distance = BIG u.pre = None s.color = vertexColors.GRAY s.distance = 0 s.pre = None q = deque() q.append(s) while len(q) > 0: u = q.popleft() for v,w in g[u]: if v.color != vertexColors.BLACK: if (u.distance + w) < v.distance: v.color = vertexColors.GRAY v.distance = u.distance + w v.pre = u q.append(v) u.color = vertexColors.BLACK def generate_edges(graph): edges = [] for node in graph: for neighbour in graph[node]: edges.append((node, neighbour)) return edges print generate_edges(graph) bfs(graph,a) bfsw(wgraph,a) for v in wgraph.keys(): print v.id+": " print "\t"+str(v.pre) print "\t"+str(v.color)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question