Skip to content

Commit a3df9c2

Browse files
authored
Create 1192.Critical-Connections-in-a-Network.cpp
1 parent 93c5761 commit a3df9c2

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class Solution {
2+
vector<vector<int>>rets;
3+
vector<vector<int>>next;
4+
int time = 0;
5+
public:
6+
vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections)
7+
{
8+
next.resize(n);
9+
for (auto x:connections)
10+
{
11+
next[x[0]].push_back(x[1]);
12+
next[x[1]].push_back(x[0]);
13+
}
14+
15+
vector<bool>visited(n);
16+
vector<int>dfn(n,0);
17+
vector<int>low(n,0);
18+
vector<int>parent(n,-1);
19+
20+
for (int i = 0; i < n; i++)
21+
{
22+
if (visited[i] == false)
23+
DFS(i, visited, dfn, low, parent);
24+
}
25+
26+
return rets;
27+
}
28+
29+
30+
void DFS(int u, vector<bool>&visited, vector<int>&dfn, vector<int>&low, vector<int>&parent)
31+
{
32+
visited[u] = true;
33+
34+
dfn[u] = low[u] = ++time;
35+
36+
for (int v : next[u])
37+
{
38+
if (v == parent[u])
39+
continue;
40+
41+
if (!visited[v])
42+
{
43+
parent[v] = u;
44+
DFS(v, visited, dfn, low, parent);
45+
46+
if (low[v] > dfn[u]) rets.push_back({v,u}); // critical edge
47+
48+
// if(low[v] >= dfn[u]), then u is a critical vertex
49+
50+
low[u] = min(low[u], low[v]);
51+
}
52+
else
53+
{
54+
low[u] = min(low[u], dfn[v]);
55+
}
56+
}
57+
}
58+
59+
};

0 commit comments

Comments
 (0)