-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathCritical Connections in a Network.java
37 lines (29 loc) · 1.94 KB
/
Critical Connections in a Network.java
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
// Runtime: 79 ms (Top 74.61%) | Memory: 107.90 MB (Top 55.73%)
class Solution {
// We record the timestamp that we visit each node. For each node, we check every neighbor except its parent and return a smallest timestamp in all its neighbors. If this timestamp is strictly less than the node's timestamp, we know that this node is somehow in a cycle. Otherwise, this edge from the parent to this node is a critical connection
public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {
List<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();
for(List<Integer> oneConnection :connections) {
graph[oneConnection.get(0)].add(oneConnection.get(1));
graph[oneConnection.get(1)].add(oneConnection.get(0));
}
int timer[] = new int[1];
List<List<Integer>> results = new ArrayList<>();
boolean[] visited = new boolean[n];
int []timeStampAtThatNode = new int[n];
criticalConnectionsUtil(graph, -1, 0, timer, visited, results, timeStampAtThatNode);
return results;
}
public void criticalConnectionsUtil(List<Integer>[] graph, int parent, int node, int timer[], boolean[] visited, List<List<Integer>> results, int []timeStampAtThatNode) {
visited[node] = true;
timeStampAtThatNode[node] = timer[0]++;
int currentTimeStamp = timeStampAtThatNode[node];
for(int oneNeighbour : graph[node]) {
if(oneNeighbour == parent) continue;
if(!visited[oneNeighbour]) criticalConnectionsUtil(graph, node, oneNeighbour, timer, visited, results, timeStampAtThatNode);
timeStampAtThatNode[node] = Math.min(timeStampAtThatNode[node], timeStampAtThatNode[oneNeighbour]);
if(currentTimeStamp < timeStampAtThatNode[oneNeighbour]) results.add(Arrays.asList(node, oneNeighbour));
}
}
}