【leetcode】684. Redundant Connection

提交代碼

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;
 	}
}

運行結果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章