1
- // Runtime: 1262 ms (Top 24.62%) | Memory: 179.7 MB (Top 55.22%)
2
1
class Solution {
2
+ int timer = 1 ;
3
3
public:
4
- vector<vector<int >>ans;
5
-
6
- void dfs (vector<vector<int >>&graph , int node , int parent , vector<bool >&vis , int & ct , vector<int >&time , vector<int >&low){
7
- vis[node] = 1 ;
8
- time [node] = ct;
9
- low[node] = ct++;
10
- for (auto value : graph[node]){
11
- if (value == parent)continue ;
12
- if (!vis[value]){
13
- dfs (graph , value , node , vis , ct , time , low);
14
- low[node] = min (low[node] , low[value]);
15
-
16
- if (low[value] > time [node]){
17
- ans.push_back ({node , value});
18
- }
19
- }else {
20
- low[node] = min (low[node] , time [value]);
21
- }
4
+ void dfs (vector<int >adj[] , int node , int parent , vector<int >&tin , vector<int >&low , vector<int >&vis , vector<vector<int >>&ans)
5
+ {
6
+ vis[node] = 1 ;
7
+ tin[node] = low[node] = timer;
8
+ timer++;
9
+ for (auto it:adj[node])
10
+ {
11
+ if (it == parent) continue ;
12
+ if (vis[it] == 0 )
13
+ {
14
+ dfs (adj , it , node , tin , low , vis , ans);
15
+ low[node] = min (low[node] , low[it]);
16
+ if (tin[node] < low[it])
17
+ ans.push_back ({node , it});
22
18
}
23
- }
24
-
25
- vector<vector<int >> criticalConnections (int n, vector<vector<int >>& connections) {
26
- ans.clear ();
27
- vector<vector<int >>graph (n);
28
-
29
- for (int i = 0 ; i < connections.size () ; i += 1 ){
30
- int a = connections[i][0 ];
31
- int b = connections[i][1 ];
32
-
33
- graph[a].push_back (b);
34
- graph[b].push_back (a);
19
+ else
20
+ {
21
+ low[node] = min (low[node] , low[it]);
35
22
}
36
-
37
- vector<bool >vis (n , false );
38
- vector<int >time (n , -1 );
39
- vector<int >low (n , -1 );
40
- int ct = 0 ;
41
- for (int i = 0 ; i < n ; i += 1 ){
42
- if (!vis[i]){
43
- dfs (graph , i , -1 , vis , ct , time , low);
44
- }
23
+ }
24
+ }
25
+ vector<vector<int >> criticalConnections (int n, vector<vector<int >>& con) {
26
+ vector<int >adj[n];
27
+ for (int i = 0 ;i<con.size ();i++)
28
+ {
29
+ adj[con[i][0 ]].push_back (con[i][1 ]);
30
+ adj[con[i][1 ]].push_back (con[i][0 ]);
45
31
}
46
-
32
+ vector<vector<int >>ans;
33
+ vector<int >vis (n , 0 ) , tin (n , 0 ) , low (n , 0 );
34
+ dfs (adj , 0 , -1 , tin , low , vis , ans);
47
35
return ans;
48
36
}
49
37
};
0 commit comments