684.冗余连接
684.冗余连接
2:10
// 定义并查集类
class UnionFind{
// 构造函数初始化并查集
constructor(n){
this.parent = new Array(n).fill(0).map((item,index)=>index)
this.rank = new Array(n).fill(1)
this.count = n
}
// 查找元素的根节点
find(x){
if(this.parent[x] !== x){
this.parent[x] = this.find(this.parent[x])
}
return this.parent[x]
}
// 合并两个集合
union(x,y){
let rootX = this.find(x)
let rootY = this.find(y)
if(rootX === rootY){
return false
}
if(this.rank[rootX] < this.rank[rootY]){
this.parent[rootX] = rootY
this.rank[rootY] += this.rank[rootX]
}else{
this.parent[rootY] = rootX
this.rank[rootX] += this.rank[rootY]
}
this.count--
}
// 判断两个元素是否属于同一个集合
connected(x,y){
return this.find(x) === this.find(y)
}
// 获取集合的数量
getCount(){
return this.count
}
}
/**
* @param {number[][]} edges
* @return {number[]}
*/
var findRedundantConnection = function(edges) {
let len=edges.length
let uf = new UnionFind(len)
for(let i=0;i<len;i++){
if(!uf.connected(edges[i][0],edges[i][1])){
uf.union(edges[i][0],edges[i][1])
}else{
return edges[i]
}
}
return []
};
-------------------
function findRedundantConnection(edges) {
// 用于存储图的邻接表
const graph = new Map();
function dfs(source, target) {
// 用于记录已经访问过的节点
const visited = new Set();
const stack = [source];
while (stack.length > 0) {
const node = stack.pop();
if (node === target) {
return true;
}
if (!visited.has(node)) {
visited.add(node);
const neighbors = graph.get(node);
if (neighbors) {
for (const neighbor of neighbors) {
if (!visited.has(neighbor)) {
stack.push(neighbor);
}
}
}
}
}
return false;
}
for (const [u, v] of edges) {
if (graph.has(u) && graph.has(v) && dfs(u, v)) {
// 如果添加这条边会形成环,返回这条边
return [u, v];
}
// 添加这条边到图中
if (!graph.has(u)) {
graph.set(u, new Set());
}
if (!graph.has(v)) {
graph.set(v, new Set());
}
graph.get(u).add(v);
graph.get(v).add(u);
}
return [];
}

浙公网安备 33010602011771号