There are n
servers numbered from 0
to n - 1
connected by undirected server-to-server connections
forming a network where connections[i] = [ai, bi]
represents a connection between servers ai
and bi
. Any server can reach other servers directly or indirectly through the network.
A critical connection is a connection that, if removed, will make some servers unable to reach some other server.
Return all critical connections in the network in any order.
Example 1:
Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]] Output: [[1,3]] Explanation: [[3,1]] is also accepted.
Example 2:
Input: n = 2, connections = [[0,1]] Output: [[0,1]]
Constraints:
2 <= n <= 105
n - 1 <= connections.length <= 105
0 <= ai, bi <= n - 1
ai != bi
- There are no repeated connections.
class Solution {
public:
int count = 0;
vector<int> dfn, low;
vector<vector<int>> graph;
vector<vector<int>> res;
void tarjan(int u, int fa) {
dfn[u] = low[u] = ++count;
for (auto& v : graph[u]) {
if (v == fa)
continue;
if (!dfn[v]) {
tarjan(v, u);
low[u] = min(low[u], low[v]);
if (dfn[u] < low[v])
res.push_back({u, v});
} else {
low[u] = min(dfn[v], low[u]);
}
}
}
vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) {
dfn.resize(n);
low.resize(n);
graph.resize(n);
for (auto& edge : connections) {
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
}
for (int i = 0; i < n; i++) {
if (!dfn[i])
tarjan(i, -1);
}
return res;
}
};