两种图的遍历算法:广度优先(BFS)与深度优先(DFS)。
广度优先遍历的路径通常短而直接,深度优先遍历的路径通常长而曲折。
广度优先遍历
从起点开始,遍历所有与起点连通的顶点,再遍历与这些顶点连通的顶点,即先搜索距离起点距离为1的顶点,再遍历与起点距离为2的顶点…..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| def bfsTravel(graph, source): ''' 广度优先遍历 INPUT -> 用邻接表存储的图, 开始遍历的源节点 ''' frontiers = [source] travel = [source] while frontiers: nexts = [] for frontier in frontiers: for current in graph[frontier]: if current not in travel: travel.append(current) nexts.append(current) frontiers = nexts return travel
if __name__ == '__main__':
Graph = {'A': ['B', 'C', 'D'], 'B': ['E'], 'C': ['D', 'F'], 'D': ['B', 'E', 'G'], 'E': [], 'F': ['D', 'G'], 'G': ['E']} r = bfsTravel(Graph, 'A') print(r)
|
深度优先遍历
从起点开始选择一条边走到下一个顶点,每到一个顶点便标记此顶点已到达,当来到一个标记过的顶点时回退到上一个顶点,再选择一条没有到达过的顶点……直到所有顶点都被访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| def dfsTravel(graph, source): ''' 深度优先遍历 INPUT -> 用邻接表存储的图, 开始遍历的源节点 ''' travel = [] stack = [source] while stack: current = stack.pop() if current not in travel: travel.append(current) for next_adj in graph[current]: if next_adj not in travel: stack.append(next_adj) return travel
if __name__ == '__main__':
Graph = {'A': ['B', 'C', 'D'], 'B': ['E'], 'C': ['D', 'F'], 'D': ['B', 'E', 'G'], 'E': [], 'F': ['D', 'G'], 'G': ['E']} r = dfsTravel(Graph, 'A') print(r)
|