Find the Weak Connected Component in the Directed Graph
Find the number Weak Connected Component in the directed graph. Each node in the graph contains a label and a list of its neighbors. (a connected set of a directed graph is a subgraph in which any two vertices are connected by direct edge path.
Example
Given graph:
A----->B C
\ | |
\ | |
\ | |
\ v v
->D E <- F
Return {A,B,D}, {C,E,F}
. Since there are two connected component which are {A,B,D} and {C,E,F}
这题和Find the Connected Component in the Undirected Graph看起来是很一样的题目,但是实际上在有向图中的弱连通区域是无法走通的。所以使用DFS无法解决这个问题。那么Union Find 并查集就可以出马了,毕竟它不要求边的方向,只要求连接。所以在这题里面,如果一条边的两个结点有未出现的,则先加入点。之后再对每条边的两个结点做按秩合并。所以并查集的实现,这里需要使用hashmap来保存已有结点,实时加入。这题还有一个问题,就是如何输出最后的弱连接块。显然这里的弱连接块,每块的结点的father最终都是同一个,按这个进行查找。代码如下:
# Definition for a directed graph node # class DirectedGraphNode: # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution: # @param {DirectedGraphNode[]} nodes a array of directed graph node # @return {int[][]} a connected set of a directed graph def connectedSet2(self, nodes): hashmap = {} UF = UnionFind() for node in nodes: if node.label not in hashmap: hashmap[node.label] = node.label UF.add(node.label) for neighbor in node.neighbors: if neighbor.label not in hashmap: hashmap[neighbor.label] = neighbor.label UF.add(neighbor.label) UF.union(node.label, neighbor.label) res = {} for i in hashmap.keys(): father = UF.find(i) if father not in res: res[father] = [i] else: res[father].append(i) ans = map(sorted,res.values()) return ans class UnionFind(object): def __init__(self): self.id = {} self.sz = {} def add(self, x): self.id[x] = x self.sz[x] = 1 def find(self,x): while x != self.id[x]: self.id[x] = self.id[self.id[x]] x = self.id[x] return x def union(self, x, y): i = self.find(x) j = self.find(y) if i != j: if self.sz[i] < self.sz[j]: i, j = j, i self.id[j] = i #j is added to i self.sz[i] += self.sz[j]
并查集的结点数目为V,边的数目为E,合并操作一共是E个,所以最终的复杂度是O(V+E)级别的,最终输出结果的复杂度最坏是O(VlogV)级别的,最坏全部在一个弱联通块里面。
posted on 2016-07-06 14:43 Sheryl Wang 阅读(243) 评论(0) 编辑 收藏 举报