-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathRedundantConnection.java
More file actions
31 lines (26 loc) · 882 Bytes
/
RedundantConnection.java
File metadata and controls
31 lines (26 loc) · 882 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public int[] findRedundantConnection(int[][] edges) {
int m = edges.length;
Map<Integer, Set<Integer>> map = new HashMap<>();
for (int i = 1; i <= m; i++) {
map.put(i, new HashSet<>());
}
for (int[] edge : edges) {
if (dfs(new HashSet<>(), map, edge[0], edge[1])) return edge;
map.get(edge[0]).add(edge[1]);
map.get(edge[1]).add(edge[0]);
}
return null;
}
private boolean dfs(Set<Integer> visited, Map<Integer, Set<Integer>> map,
int src, int target) {
if (src == target) return true;
visited.add(src);
for (int next : map.get(src)) {
if (!visited.contains(next)) {
if (dfs(visited, map, next, target)) return true;
}
}
return false;
}
}