ID | Title | Difficulty | |
---|---|---|---|
Loading... |
684. Redundant Connection
Medium
LeetCode
Depth-First Search, Breadth-First Search, Union Find, Graph
Problem
In this problem, a tree is an undirected graph that is connected and has no cycles.
You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where $edges[i] = [a_i, b_i]$ indicates that there is an edge between nodes $a_i$ and $b_i$ in the graph.
Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.
Example 1:
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Example 2:
Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output: [1,4]
Constraints:
- n == edges.length
- 3 <= n <= 1000
- edges[i].length == 2
- $1 <= a_i < b_i <= edges.length$
- $a_i != b_i$
- There are no repeated edges.
- The given graph is connected.
Code
class Solution {
public class UnionFind {
int[] parents;
int[] ranks;
public UnionFind(int n) {
parents = new int[n];
ranks = new int[n];
for (int i = 0; i < n; i++) {
parents[i] = i;
ranks[i] = 1;
}
}
public boolean union(int x, int y) {
int xParent = find(x);
int yParent = find(y);
if (xParent == yParent) return false;
if (ranks[xParent] > ranks[yParent]) {
parents[yParent] = xParent;
} else if (ranks[xParent] < ranks[yParent]) {
parents[xParent] = yParent;
} else {
parents[yParent] = xParent;
ranks[xParent]++;
}
return true;
}
public int find(int node) {
if(node == parents[node]) return node;
return find(parents[node]);
}
}
UnionFind node;
public int[] findRedundantConnection(int[][] edges) {
node = new UnionFind(edges.length + 1);
for(int[] edge : edges){
if(!node.union(edge[0], edge[1])){
return edge;
}
}
return new int[]{-1, -1};
}
}
class Solution {
public int[] findRedundantConnection(int[][] edges) {
HashMap<Integer, List<Integer>> graph = new HashMap<>();
for(int[] edge : edges) {
HashSet<Integer> visited = new HashSet<>();
// 添加边之前看是否已经有连接
if(helper(graph, visited, edge[0], edge[1])) {
return edge;
} else {
if(!graph.containsKey(edge[0])) {
graph.put(edge[0], new ArrayList<>());
}
graph.get(edge[0]).add(edge[1]);
if(!graph.containsKey(edge[1])) {
graph.put(edge[1], new ArrayList<>());
}
graph.get(edge[1]).add(edge[0]);
}
}
return new int[]{-1, -1};
}
private boolean helper(
HashMap<Integer, List<Integer>> graph,
HashSet<Integer> visited,
int x,
int y
) {
if(x == y) return true;
if(!graph.containsKey(x)) return false;
for(int sub : graph.get(x)) {
if(!visited.add(sub)) continue;
if(helper(graph, visited, sub, y)) return true;
}
return false;
}
}
按 <- 键看上一题!
682. Baseball Game
按 -> 键看下一题!
686. Repeated String Match