[Leetcode]Graph & Union Find
来源:互联网 发布:java异常处理设计 编辑:程序博客网 时间:2024/06/09 14:13
Graph & Union Find
This time, I will talk about how to use union find
to evaluate if there is a cycle in the graph. Union find
is a useful method to evaluate the existence of a cycle in an undirected graph, so I will firstly solve a problem by doing so. But actually, this algorithm can even be used to evaluate the existence of a cycle in a directed graph, but it has to satisfied some prerequisites.
[684] Redundant Connection
Description
Analysis
It is easy to understand the problem. What we need to do is to find the last edge leading to the existence of cycle. We can define an array unionSet
to record the parents of the node. At first, we initialize the unionSet as unionSets[i] = i
. If there is an undirected edge 1-2
, then unionSet[unionSet[2]] = 1. The following graph represents a special case. In this case, when edge A
comes, unionSet[2] = 1; and then when edge B
comes, unionSet[unionSet[2]] = 3. That is, 1, 2 and 3 are connected together. So, if there is an edge, 1-3
, we know that unionSet[1] = 3 and unionSets[3] = 3, that means, this two node has already connected together so this edge will lead to the existence of cycle.
Code
#include <iostream>#include <vector>using namespace std;class Solution {private: int unionFind(int index, vector<int>& sets) { if (sets[index] == index) { return index; } else { sets[index] = unionFind(sets[index], sets); return sets[index]; } }public: vector<int> findRedundantConnection(vector<vector<int>>& edges) { int size = edges.size(); vector<int> sets(size + 1, 0); for (int i = 0; i <= size; i++) { sets[i] = i; } vector<int> result; for (auto each : edges) { if (unionFind(each[0], sets) == unionFind(each[1], sets)) { result = each; } else { sets[unionFind(each[1], sets)] = unionFind(each[0], sets); } } return result; }};int main() { std::vector<std::vector<int>> v{{1,4},{3,4},{1,3},{1,2},{4,5}}; Solution so; std::vector<int> result = so.findRedundantConnection(v); cout << result[0] << " " << result[1] << endl; return 0;}
Time complexity: O(n)
[685] Redundant Connection II
Description
Analysis
At the last problem, the graph is undirected so it will be easy to evaluate the existence of cycle by union find
. But now, the graph is directed. The things are still easy.
At first, as the problem’s description said, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents
, so every node has at most one parent. If a node has two parents, one of its edge connected to its parents should be removed.
Secondly, there shouldn’t be any cycle in the graph.
All in all, if there isn’t any node which has more than 1 parents, then we can just remove the last edge which is leading to the existence of cycle. In this case, we can still use union find
because all of the nodes have at most 1 in-degree. If no cycle exists, then we can just remove the second edge which has the same child. What if there are a cycle and the node which has two parents? We have to use a trick. We can set the candidate B invalid, if the cycle doesn’t exist anymore, we know that the candidate B lead to the existence of the cycle. But if the cycle still exists, we know that candidate A lead to the existence of the cycle.
1) Check whether there is a node having two parents. If so, store them as candidates A and B, and set the second edge invalid. 2) Perform normal union find. If the tree is now valid simply return candidate B else if candidates not existing we find a circle, return current edge; else remove candidate A instead of B.
Code
class Solution {public: vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) { int n = edges.size(); vector<int> parent(n+1, 0), candA, candB; // step 1, check whether there is a node with two parents for (auto &edge:edges) { if (parent[edge[1]] == 0) parent[edge[1]] = edge[0]; else { candA = {parent[edge[1]], edge[1]}; candB = edge; edge[1] = 0; } } // step 2, union find for (int i = 1; i <= n; i++) parent[i] = i; for (auto &edge:edges) { if (edge[1] == 0) continue; int u = edge[0], v = edge[1], pu = root(parent, u); // Now every node only has 1 parent, so root of v is implicitly v if (pu == v) { if (candA.empty()) return edge; return candA; } parent[v] = pu; } return candB; }private: int root(vector<int>& parent, int k) { if (parent[k] != k) parent[k] = root(parent, parent[k]); return parent[k]; }};
Time Complexity: O(n)
- [Leetcode]Graph & Union Find
- [Leetcode] Union Find
- leetcode:Union Find:Surrounded Regions(130)
- LeetCode基础--Union Find(Disjoint Set)
- Union Find
- Union-Find
- Union-find
- Union-Find
- union find
- union-find
- Geeks - Union-Find Algorithm - Detect Cycle in a an Undirected Graph算法
- LeetCode Union-Find(并查集) 专题(一)
- LeetCode Union-Find(并查集) 专题(二)
- LeetCode[Graph]: Clone Graph
- LeetCode:Graph,
- Dynamic connectivity --Union-Find
- UVa11987 Almost Union-Find
- UVA11987- Almost Union-Find
- QT5获取本机信息
- Oracle连接数过多释放机制
- poj1651 Multiplication Puzzle(区间dp)
- Python3 pandas read_csv 读取txt文件报错:IOError: Initializing from file failed
- 基于注解的Spring Security原理解析
- [Leetcode]Graph & Union Find
- Spring+SpringMVC+MyBatis+easyUI整合进阶篇(十一)redis密码设置、安全设置
- # C#调用已经使用Python训练好的神经网络做图片检测
- Bandwagon的vps设置vpn代理
- 将linux(ubuntu)安装到U盘下面--便携式ubuntu和使用dd制作U盘安装工具
- 技术分享连载(八十)
- C/C++ 第八周串和数组 (一)顺序串算法 项目2—(一)
- 算符优先系列之(一)Firstvt和Lastvt集
- 360检测Dedecms重定向漏洞的解决方案