|
| 1 | +/** |
| 2 | + * 1192. Critical Connections in a Network |
| 3 | + * https://leetcode.com/problems/critical-connections-in-a-network/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections |
| 7 | + * forming a network where connections[i] = [ai, bi] represents a connection between servers ai and |
| 8 | + * bi. Any server can reach other servers directly or indirectly through the network. |
| 9 | + * |
| 10 | + * A critical connection is a connection that, if removed, will make some servers unable to reach |
| 11 | + * some other server. |
| 12 | + * |
| 13 | + * Return all critical connections in the network in any order. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number} n |
| 18 | + * @param {number[][]} connections |
| 19 | + * @return {number[][]} |
| 20 | + */ |
| 21 | +var criticalConnections = function(n, connections) { |
| 22 | + const graph = Array.from({ length: n }, () => []); |
| 23 | + const discoveryTimes = new Array(n).fill(-1); |
| 24 | + const lowestReachableTimes = new Array(n).fill(-1); |
| 25 | + const criticalEdges = []; |
| 26 | + let time = 0; |
| 27 | + |
| 28 | + connections.forEach(([from, to]) => { |
| 29 | + graph[from].push(to); |
| 30 | + graph[to].push(from); |
| 31 | + }); |
| 32 | + |
| 33 | + exploreNode(0, -1); |
| 34 | + |
| 35 | + return criticalEdges; |
| 36 | + |
| 37 | + function exploreNode(current, parent) { |
| 38 | + discoveryTimes[current] = lowestReachableTimes[current] = time++; |
| 39 | + |
| 40 | + for (const neighbor of graph[current]) { |
| 41 | + if (neighbor === parent) continue; |
| 42 | + if (discoveryTimes[neighbor] === -1) { |
| 43 | + exploreNode(neighbor, current); |
| 44 | + lowestReachableTimes[current] = Math.min( |
| 45 | + lowestReachableTimes[current], |
| 46 | + lowestReachableTimes[neighbor] |
| 47 | + ); |
| 48 | + if (lowestReachableTimes[neighbor] > discoveryTimes[current]) { |
| 49 | + criticalEdges.push([current, neighbor]); |
| 50 | + } |
| 51 | + } else { |
| 52 | + lowestReachableTimes[current] = Math.min( |
| 53 | + lowestReachableTimes[current], |
| 54 | + discoveryTimes[neighbor] |
| 55 | + ); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | +}; |
0 commit comments