package com.heu.wsq.leetcode.graph;
/**
* 684. 冗余连接
* @author wsq
* @date 2021/1/13
* 在本问题中, 树指的是一个连通且无环的无向图。
* 输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, ..., N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。
* 结果图是一个以边组成的二维数组。每一个边的元素是一对[u, v] ,满足 u < v,表示连接顶点u 和v的无向图的边。
* 返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边 [u, v] 应满足相同的格式 u < v。
*
* 示例 1:
* 输入: [[1,2], [1,3], [2,3]]
* 输出: [2,3]
* 解释: 给定的无向图为:
* 1
* / \
* 2 - 3
*
* 链接:https://leetcode-cn.com/problems/redundant-connection
*/
public class FindRedundantConnection {
public int[] findRedundantConnection(int[][] edges){
int n = edges.length;
UnionFind unionFind = new UnionFind(n);
for (int i = 0; i < n; i++){
int[] edge = edges[i];
if (unionFind.isConnected(edge[0], edge[1])){
return edge;
}
unionFind.union(edge[0], edge[1]);
}
return new int[0];
}
private class UnionFind{
private int[] parent;
private int[] rank;
public UnionFind(int n){
this.parent = new int[n];
this.rank = new int[n];
// 初始化数组内容
for(int i = 0; i < n; i++){
this.parent[i] = i;
this.rank[i] = 1;
}
}
public void union(int x, int y){
x = x - 1;
y = y - 1;
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY){
return;
}
if (this.rank[rootX] == this.rank[rootY]){
this.parent[rootX] = rootY;
this.rank[rootY] += 1;
}else if (this.rank[rootX] > this.rank[rootY]){
this.parent[rootY] = rootX;
}else{
this.parent[rootX] = rootY;
}
}
public int find(int x){
x -= 1;
int r = x;
while (r != this.parent[r]){
r = this.parent[r];
}
int k = x;
while (k != r){
int tmp = this.parent[k];
this.parent[k] = r;
k = tmp;
}
return r;
}
public boolean isConnected(int x, int y){
x -= 1;
y -= 1;
int rootX = find(x);
int rootY = find(y);
return rootX == rootY;
}
}
}
684. 冗余连接(并查集)
博客涉及图论和并查集相关信息技术知识,可能与leetcode题目相关,虽无具体内容,但推测围绕这些技术领域展开探讨。

被折叠的 条评论
为什么被折叠?



