|
| 1 | +/** |
| 2 | + * @param {number} n |
| 3 | + * @param {number[][]} connections |
| 4 | + * @return {number[][]} |
| 5 | + */ |
| 6 | +function criticalConnections(n, connections) { |
| 7 | + const critical = []; |
| 8 | + const graph = buildGraph(n, connections); |
| 9 | + // console.log({graph}) |
| 10 | + |
| 11 | + for (let i = 0; i < connections.length; i++) { // O(|E| * [|V|^3 + |V|^2|E|]) = O(|V|^3|E| + |V|^2|E|^2) |
| 12 | + const link = connections[i]; |
| 13 | + if (isLinkCritical(link, graph)) { |
| 14 | + critical.push(link); |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + return critical; |
| 19 | +} |
| 20 | + |
| 21 | +function buildGraph(n, connections) { |
| 22 | + const graph = [...Array(n).keys()].reduce((map, i) => { |
| 23 | + map.set(i, new Set()); |
| 24 | + return map; |
| 25 | + }, new Map()); |
| 26 | + |
| 27 | + connections.forEach(([i, j]) => { |
| 28 | + const iAdj = graph.get(i); |
| 29 | + iAdj.add(j); |
| 30 | + const jAdj = graph.get(j); |
| 31 | + jAdj.add(i); |
| 32 | + }); |
| 33 | + |
| 34 | + return graph; |
| 35 | +} |
| 36 | + |
| 37 | +function isLinkCritical(link, graph) { // DFS: O(|V|^2 * |E|+|V|) = O(|V|^3 + |V|^2|E|) |
| 38 | + for (let i = 0; i < graph.size; i++) { |
| 39 | + for (let j = 0; j < graph.size; j++) { |
| 40 | + if (hasLink([i, j], link)) continue; |
| 41 | + if (!isConnected(i, j, link, graph)) { // DFS: O(|E|+|V|) |
| 42 | + // console.log({i, j, link}); |
| 43 | + return true; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return false; |
| 49 | +} |
| 50 | + |
| 51 | +function hasLink(a, b) { |
| 52 | + return (a[0] === b[0] && a[1] === b[1]) || (a[0] === b[1] && a[1] === b[0]); |
| 53 | +} |
| 54 | + |
| 55 | +// DFS: O(|E|+|V|) |
| 56 | +function isConnected(i, j, ignoreLink, graph, seen = new Set()) { |
| 57 | + if (i === j) return true; |
| 58 | + if (graph.get(i).has(j)) return true; |
| 59 | + |
| 60 | + for (const adj of graph.get(i)) { |
| 61 | + if (hasLink([i, adj], ignoreLink)) continue; |
| 62 | + |
| 63 | + if (seen.has(adj)) continue; |
| 64 | + seen.add(adj); |
| 65 | + |
| 66 | + if (isConnected(adj, j, ignoreLink, graph, seen)) { |
| 67 | + return true; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + return false; |
| 72 | +} |
| 73 | + |
| 74 | +module.exports = criticalConnections; |
0 commit comments