There are n
servers numbered from 0
to n-1
connected by undirected server-to-server connections
forming a network where connections[i] = [a, b]
represents a connection between servers a
and b
. Any server can reach any other server directly or indirectly through the network.
A critical connection is a connection that, if removed, will make some server 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.
Constraints:
1 <= n <= 10^5
n-1 <= connections.length <= 10^5
connections[i][0] != connections[i][1]
- There are no repeated connections.
class Solution {
public:
vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections)
{
vector<vector<int>> nodes(n) ;
for(auto connect : connections)
{
nodes[connect[0]].push_back(connect[1]) ;
nodes[connect[1]].push_back(connect[0]) ;
}
vector<vector<int>> res ;
vector<int> parent(n , -1) , dfn(n , -1) , low(n , -1) , visited(n , 0) ;
for(int i = 0 ; i < n ; ++i)
{
if(visited[i]) continue ;
tarjan(i , nodes , parent , dfn , low , visited , res) ;
}
return res ;
}
void tarjan(int node , vector<vector<int>>&nodes , vector<int>&parent , vector<int>&dfn , vector<int>&low , vector<int>&visited , vector<vector<int>>&res )
{
visited[node] = 1 ;
dfn[node] = ++time ;
low[node] = dfn[node] ;
for(auto cne_node : nodes[node])
{
if(!visited[cne_node])
{
parent[cne_node] = node ;
tarjan(cne_node , nodes , parent , dfn , low , visited , res) ;
low[node] = min(low[node] , low[cne_node]) ;
if(low[cne_node] > dfn[node]) res.push_back({node , cne_node}) ;
}
else if(cne_node != parent[node])
{
low[node] = min(low[node] , dfn[cne_node]) ;
}
}
}
private :
int time = 0 ;
};