请找出有向图中弱连通分量。图中的每个节点包含 1 个标签和1 个相邻节点列表。(有向图的弱连通分量是任意两点均有有向边相连的极大子图)
将连通分量内的元素升序排列。
在线评测地址:LintCode 领扣
图模型说明:
Graph
For example:
{1,2,4#2,1,4#3,5#4,1,2#5,3}
represents follow graph:
1------2 3
\ | |
\ | |
\ | |
\ | |
4 5
we use #
to split each node information.
1,2,4
represents that 2
, 4
are 1
's neighbors
2,1,4
represents that 1
, 4
are 2
's neighbors
3,5
represents that 5
is 3
's neighbor
4,1,2
represents that 1
, 2
are 4
's neighbors
5,3
represents that 3
is 5
's neighbor
样例 1:
输入: {1,2,4#2,4#3,5#4#5#6,5}
输出: [[1,2,4],[3,5,6]]
解释:
1----->2 3-->5
\ | ^
\ | |
\ | 6
\ v
->4
样例 2:
输入: {1,2#2,3#3,1}
输出: [[1,2,3]]
【题解】
算法:并查集
并查集是一种可以动态维护若干个不重叠的集合,并支持合并与查询两种操作的一种数据结构
一般我们建立一个数组fahttps://www.jiuzhang.com/solution/find-the-weak-connected-component-in-the-directed-graph/或者用map表示一个并查集,fa[i]表示i的父节点。
- 初始化:每一个点都是一个集合,因此自己的父节点就是自己fa[i]=i
- 查询:每一个节点不断寻找自己的父节点,若此时自己的父节点就是自己,那么该点为集合的根结点,返回该点。
- 修改:合并两个集合只需