const graph = {
0: [1, 2],
1: [0, 2],
2: [0, 1, 3],
3: [2, 4],
4: [3]
};
function findBridges(graph) {
const n = Object.keys(graph).length;
const visited = new Array(n).fill(false);
const disc = new Array(n).fill(-1);
const low = new Array(n).fill(-1);
const bridges = [];
let time = 0;
function dfs(u, parent) {
visited[u] = true;
disc[u] = low[u] = time++;
for (const v of graph[u]) {
if (!visited[v]) {
dfs(v, u);
low[u] = Math.min(low[u], low[v]);
if (low[v] > disc[u]) {
bridges.push([u, v]);
}
} else if (v !== parent) {
low[u] = Math.min(low[u], disc[v]);
}
}
}
for (let i = 0; i < n; i++) {
if (!visited[i]) dfs(i, -1);
}
return bridges;
}
console.log(findBridges(graph));The edges (2,3) and (3,4) are bridges because removing them increases the number of connected components. The other edges are part of cycles.
The 'low' value of a node is the smallest discovery time reachable from that node or its descendants, including back edges.
function findBridges(graph) {
const n = Object.keys(graph).length;
const visited = new Array(n).fill(false);
const disc = new Array(n).fill(-1);
const low = new Array(n).fill(-1);
const bridges = [];
let time = 0;
function dfs(u, parent) {
visited[u] = true;
disc[u] = low[u] = time++;
for (const v of graph[u]) {
if (!visited[v]) {
dfs(v, u);
low[u] = Math.min(low[u], low[v]);
if (low[v] >= disc[u]) {
bridges.push([u, v]);
}
} else if (v !== parent) {
low[u] = Math.min(low[u], disc[v]);
}
}
}
for (let i = 0; i < n; i++) {
if (!visited[i]) dfs(i, -1);
}
return bridges;
}The condition 'low[v] >= disc[u]' is incorrect for bridges; it should be 'low[v] > disc[u]'. Using '>=' causes edges that are not bridges to be included.
const graph = {
0: [1, 2],
1: [0, 2, 3],
2: [0, 1, 4],
3: [1, 5],
4: [2],
5: [3, 6],
6: [5]
};
// Assume correct Tarjan's algorithm is run on this graph.The bridges are edges (1,3), (2,4), (3,5), and (5,6) because removing them increases the number of connected components. The other edges are part of cycles.
DFS allows tracking the discovery time of nodes and the earliest reachable ancestor (low time), which is essential to identify bridges.
