Critical Connections in a Network LeetCode solution in JavaScript

1
var criticalConnections = function (n, connections) {
2
// Graph Formation
3
const graph = new Map();
4
connections.forEach(([a, b]) => {
5
const aconn = graph.get(a) || [];
6
const bconn = graph.get(b) || [];
7

8
aconn.push(b), bconn.push(a);
9
graph.set(a, aconn);
10
graph.set(b, bconn);
11
});
12

13
// Find Bridges
14
const bridges = [];
15
const visited = new Array(n).fill(false);
16
const tin = new Array(n).fill(-1);
17
const dis = new Array(n).fill(-1);
18

19
let time = 0;
20

21
const dfs = (node, parent = -1) => {
22
visited[node] = true;
23
++time;
24
tin[node] = time;
25
dis[node] = time;
26

27
const connections = graph.get(node);
28
for (let conn of connections) {
29
if (conn == parent) {
30
continue;
31
}
32
if (visited[conn]) {
33
dis[node] = Math.min(dis[node], tin[conn]);
34
} else {
35
dfs(conn, node);
36
dis[node] = Math.min(dis[node], dis[conn]);
37
if (dis[conn] > tin[node]) {
38
bridges.push([node, conn]);
39
}
40
}
41
}
42
};
43

44
dfs(0);
45

46
return bridges;
47
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0