提交代碼
class Solution {
Map<Integer, List<Integer>> graph=new HashMap<>();
Set<Integer> allNodes = new HashSet<>();
public int[] findRedundantConnection(int[][] edges) {
for(int[] e: edges) {
if(findPath(e[0], e[1]))
return e;
graph.computeIfAbsent(e[0], k->new ArrayList<>()).add(e[1]);
graph.computeIfAbsent(e[1], k->new ArrayList<>()).add(e[0]);
}
return null;
}
private Boolean findPath(int start, int end) {
if(!graph.containsKey(start)||!graph.containsKey(end)) return false;
for(int i=0; i<graph.get(start).size();i++) {
int curNode = graph.get(start).get(i);
if(allNodes.contains(curNode)) continue;
allNodes.add(curNode);
if(curNode == end) return true;
if(findPath(curNode, end)) return true;
allNodes.remove(curNode);
}
return false;
}
}
運行結果