1. 图结构的广度优先遍历的迭代算法
# Python3 Program to print BFS traversal from a given source vertex. # BFS(int s) traverses vertices reachable from s. from collections import defaultdict, namedtuple from typing import List, Dict class Node(object): def __init__(self, name=None, pi=None, dis=None, color='white'): self.name = name self.pi = pi self.dis = dis self.color = color class Graph: def __init__(self): # This class represents a directed graph using adjacency list representation self.graph: Dict[str, List[str]] = defaultdict(list) self.nodes: Dict[str, Node] = dict() def addEdge(self, u, v): self.graph[str(u)].append(str(v)) self.nodes.update({str(it): Node(name=str(it)) for it in [u, v] if str(it) not in self.nodes}) def BFS(self, u): queue = [] # 维护前驱节点队列, 节点第一次被访问是作为后继节点访问的,第二次是作为加入队列的目的是为了作为前驱节点再次访问 # Mark the source node as visited and enqueue it queue.append(str(u)) self.nodes[str(u)].color = 'gray' while queue: u = queue.pop(0) # 弹出前驱节点 print(u, end=">>>> ") # 获取弹出节点u的邻居节点. 若其未被访问, 标记为访问并将其入队列,都是相邻节点入列,正好满足层层迭代 for v in self.graph[u]: if self.nodes[v].color == 'white': print(v, self.nodes[v].color) self.nodes[v].color = 'gray' queue.append(v) self.nodes[str(u)].color = 'black' # Create a graph given in the above diagram g = Graph() g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(1, 2) g.addEdge(2, 0) g.addEdge(2, 3) g.addEdge(3, 3) print("Following is Breadth First Traversal (starting from vertex 2)") g.BFS(2)