defadd_node(self, node): if node notin self.nodes(): self.node_neighbors[node] = []
defadd_nodes(self, nodelist): for node in nodelist: self.add_node(node)
defadd_edge(self, edge): u, v = edge if (v notin self.node_neighbors[u]) and (u notin self.node_neighbors[v]): self.node_neighbors[u].append(v) if u != v: self.node_neighbors[v].append(u)
defadd_node_neighbors(self, node_neighbors): for k, v in node_neighbors.items(): self.add_node(k) for l in v: self.add_node(l) self.add_edge((k, l))
defnodes(self): return self.node_neighbors.keys()
1.2 深度优先搜索
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defdepth_first_search(self, root=None): order = []
defdfs(node_now): self.visited[node_now] = True order.append(node_now) for n in self.node_neighbors[node_now]: if n notin self.visited: dfs(n) if root: dfs(root) for node in self.nodes(): if node notin self.visited: dfs(node)
defbreadth_first_search(self, root=None): queue = [] order = []
defbfs(): whilelen(queue) > 0: node_now = queue.pop(0) self.visited[node_now] = True if node_now notin self.node_neighbors: continue # 遍历其所有邻居节点(包含父节点和子节点) for n in self.node_neighbors[node_now]: if (n notin self.visited) and (n notin queue): queue.append(n) order.append(n) if root: queue.append(root) order.append(root) bfs() for node in self.nodes(): if node notin self.visited: queue.append(node) order.append(node) bfs()
# 整理结果 nodes_list = None nodes_list = list(edges_list[0]) for k, v in edges_list[1:]: # 可以不判断k值,定在nodes_list中 if v notin nodes_list: nodes_list.append(v)