⬅ Previous Topic
Making a Large Island Using DSUNext Topic ⮕
Articulation Points in Graphs⬅ Previous Topic
Making a Large Island Using DSUNext Topic ⮕
Articulation Points in GraphsTopic Contents
You are given a network of n
servers numbered from 0
to n - 1
connected by undirected server-to-server connections, where each connection is represented as [a, b]
.
A critical connection is a connection that, if removed, will disconnect the network — making some servers unreachable from others.
Return all such critical connections in any order.
Note: In this problem, servers are treated as nodes of a graph, and connections as undirected edges. The goal is to find all bridges in the graph using Tarjan's Algorithm.
graph
as an adjacency list.tin[]
, low[]
and visited[]
of size n
.timer = 0
.tin[node] = low[node] = timer++
.low[node]
.low[neighbor] > tin[node]
, then [node, neighbor]
is a bridge.low[node] = min(low[node], tin[neighbor])
.function criticalConnections(n, connections) {
const graph = Array.from({ length: n }, () => []);
for (const [u, v] of connections) {
graph[u].push(v);
graph[v].push(u);
}
const tin = new Array(n).fill(-1);
const low = new Array(n).fill(-1);
const visited = new Array(n).fill(false);
const bridges = [];
let timer = 0;
function dfs(node, parent) {
visited[node] = true;
tin[node] = low[node] = timer++;
for (const neighbor of graph[node]) {
if (neighbor === parent) continue;
if (!visited[neighbor]) {
dfs(neighbor, node);
low[node] = Math.min(low[node], low[neighbor]);
if (low[neighbor] > tin[node]) {
bridges.push([node, neighbor]);
}
} else {
low[node] = Math.min(low[node], tin[neighbor]);
}
}
}
for (let i = 0; i < n; i++) {
if (!visited[i]) {
dfs(i, -1);
}
}
return bridges;
}
console.log("Bridges:", criticalConnections(4, [[0,1],[1,2],[2,0],[1,3]]));
⬅ Previous Topic
Making a Large Island Using DSUNext Topic ⮕
Articulation Points in GraphsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.