[算法导论]BFS @ Python
2015-02-10 14:59
603 查看
class Graph: def __init__(self): self.V = [] class Vertex: def __init__(self, x): self.key = x self.color = 'white' self.d = 10000 self.pi = None self.adj = [] class Solution: def BFS(self, G, s): for u in G.V: if u != s: u.color = 'white' u.d = 10000 u.pi = None s.color = 'gray' s.d = 0 s.pi = None Q = [] Q.append(s) while Q != []: u = Q.pop(0) for v in u.adj: if v.color == 'white': v.color = 'gray' v.d = u.d + 1 v.pi = u Q.append(v) u.color = 'black' if __name__ == '__main__': G = Graph() r = Vertex('r') s = Vertex('s') t = Vertex('t') u = Vertex('u') v = Vertex('v') w = Vertex('w') x = Vertex('x') y = Vertex('y') r.adj = [s, v] s.adj = [r, w] t.adj = [u, w, x] u.adj = [t, x, y] v.adj = [r] w.adj = [s, t, x] x.adj = [t, u, w, y] y.adj = [u, x] G.V = [r, s, t, u, v, w, x, y] m = Solution() m.BFS(G, s) for v in G.V: if v != s: print v.key, v.color, v.d, v.pi.key
相关文章推荐
- 基本数据结构(算法导论)与python
- python写算法导论 插入排序
- [算法导论]强连通分量 @ Python
- 算法导论 python代码 第四章
- 算法导论 python代码 第二章
- 基本数据结构(算法导论)与python
- Java实现算法导论中图的广度优先搜索(BFS)和深度优先搜索(DFS)
- [算法导论]哈希表 @ Python
- 算法导论快速排序python实现
- Python编写算法导论基本算法
- 【算法导论】图的广度优先搜索遍历(BFS)
- 【python菜鸟日记】-03算法导论-归并排序
- 【python菜鸟日记】-02算法导论-选择排序
- [算法导论]DFS @ Python
- [算法导论]迪克斯特拉算法 @ Python
- 两次BFS求树的直径(算法导论22.2-7)
- 【python菜鸟日记】-01 算法导论-插入排序
- [算法导论]merge sort @ Python
- 【算法导论】八皇后问题的算法实现(C、MATLAB、Python版)
- 算法导论—无向图的遍历(BFS+DFS,MATLAB)