遍历图最常用的有两种方式,就是你常听到的 BFS 和 DFS.

  • BFS: Breadth First Search,广度优先搜索
  • DFS: Depdth First Search,深度优先搜索

    BFS

    BFS 类似于树的层序遍历,从第一个节点开始,先访问离 A 最近的点,接着访问次近的点。我们先来构造一个图:图的遍历 - 图1
  1. from collections import deque
  2. class Queue(object):
  3. def __init__(self):
  4. self._deque = deque()
  5. def push(self, value):
  6. return self._deque.append(value)
  7. def pop(self):
  8. return self._deque.popleft()
  9. def __len__(self):
  10. return len(self._deque)
  11. def bfs(graph, start):
  12. search_queue = Queue()
  13. search_queue.push(start)
  14. searched = set()
  15. while search_queue: # 队列不为空就继续
  16. cur_node = search_queue.pop()
  17. if cur_node not in searched:
  18. yield cur_node
  19. searched.add(cur_node)
  20. for node in graph[cur_node]:
  21. search_queue.push(node)
  22. if __name__ == '__main__':
  23. GRAPH = {
  24. 'A': ['B', 'F'],
  25. 'B': ['C', 'I', 'G'],
  26. 'C': ['B', 'I', 'D'],
  27. 'D': ['C', 'I', 'G', 'H', 'E'],
  28. 'E': ['D', 'H', 'F'],
  29. 'F': ['A', 'G', 'E'],
  30. 'G': ['B', 'F', 'H', 'D'],
  31. 'H': ['G', 'D', 'E'],
  32. 'I': ['B', 'C', 'D'],
  33. }
  34. print('bfs:')
  35. bfs(GRAPH, 'A')
  36. """
  37. bfs:
  38. A
  39. B
  40. F
  41. C
  42. I
  43. G
  44. E
  45. D
  46. H
  47. """

DFS

深度优先搜索(DFS)是每遇到一个节点,如果没有被访问过,就直接去访问它的邻居节点,不断加深。代码其实很简单:

  1. DFS_SEARCHED = set()
  2. def dfs(graph, start):
  3. if start not in DFS_SEARCHED:
  4. print(start)
  5. DFS_SEARCHED.add(start)
  6. for node in graph[start]:
  7. if node not in DFS_SEARCHED:
  8. dfs(graph, node)
  9. print('dfs:')
  10. dfs(GRAPH, 'A') # A B C I D G F E H