Leetcode-1192

Critical Connections in a Network

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <vector>
#include <stack>

class Solution {
public:
    std::vector<std::vector<int>> criticalConnections(int n, std::vector<std::vector<int>>& connections) {
        adj_.resize(n);
        for (std::vector<int>& e : connections) {
            adj_[e[0]].push_back(e[1]);
            adj_[e[1]].push_back(e[0]);
        }
        
        dfn_.resize(n, -1);
        low_.resize(n, -1);
        timer_ = 0;
        
        std::vector<std::vector<int>> res;
        dfs(0, -1, res);
        return res;
    }

private:
    void dfs(int u, int parent, std::vector<std::vector<int>>& res) {
        dfn_[u] = low_[u] = ++timer_;        
        for (int v : adj_[u]) {
            if (v == parent) {
                continue;
            }
            if (dfn_[v] == -1) {
                dfs(v, u, res);
                low_[u] = std::min(low_[u], low_[v]);
                if (low_[v] > dfn_[u]) {
                    res.push_back({u, v});
                }
            }
            else {
                low_[u] = std::min(low_[u], low_[v]);
            }
        }
    }

    int timer_;
    
    std::vector<std::vector<int>> adj_;
    std::vector<int> dfn_;
    std::vector<int> low_;
};

Leetcode-1192