[leetcode] 1192. Critical Connections in a Network

class Solution {
    private int time = 0;
    public List> criticalConnections(int n, List> connections) {
        List> res = new ArrayList<>();
        List[] graph = new ArrayList[n];
        int[] dist = new int[n];
        int[] low = new int[n];
        HashSet visited = new HashSet<>();
        
        for (int i = 0; i < n; i++) {
            graph[i] = new ArrayList<>();
        }
 
        for(List edge : connections){
            int u = edge.get(0);
            int v = edge.get(1);
            graph[u].add(v);
            graph[v].add(u);
        }
        
        dfs(0, -1 , graph, visited, dist, low, res);
        
        return res;
        
    }
    
    public void dfs(int cur, int root, List[] graph, HashSet visited, int[] dist, int[] low, List> res){
        dist[cur] = time++; 
        low[cur] = dist[cur];
        visited.add(cur);
        
        for(int nei : graph[cur]){
            if(nei == root){
                continue;
            }
            //如果没访问过,继续dfs递归下去
            //cur的child的到达的最小的点,也就是cur所能到达的最小的点
            //一路backward返回
            if(!visited.contains(nei)){
                dfs(nei, cur, graph, visited, dist, low, res);
                low[cur] = Math.min(low[cur], low[nei]);
                
                if(dist[cur] < low[nei]){
                    res.add(Arrays.asList(cur, nei));
                }
            }
            // 如果访问过,那就更新cur的low
            else{
                low[cur] = Math.min(low[cur], dist[nei]);
            }
        }
        
    }
}

你可能感兴趣的:(leetcode)