Trees are a special type of graph without cycles. Shortest path problems often require handling cycles and multiple paths between nodes, which only general graphs can represent.
type Edge = { to: number; weight: number }; const tree: Edge[][] = [ [{ to: 1, weight: 2 }], [{ to: 0, weight: 2 }, { to: 2, weight: 3 }], [{ to: 1, weight: 3 }] ]; const graph: Edge[][] = [ [{ to: 1, weight: 2 }, { to: 2, weight: 4 }], [{ to: 0, weight: 2 }, { to: 2, weight: 1 }], [{ to: 0, weight: 4 }, { to: 1, weight: 1 }] ]; function dijkstra(graph: Edge[][], start: number): number[] { const dist = Array(graph.length).fill(Infinity); dist[start] = 0; const visited = new Set<number>(); while (visited.size < graph.length) { let u = -1; let minDist = Infinity; for (let i = 0; i < dist.length; i++) { if (!visited.has(i) && dist[i] < minDist) { minDist = dist[i]; u = i; } } if (u === -1) break; visited.add(u); for (const edge of graph[u]) { if (dist[u] + edge.weight < dist[edge.to]) { dist[edge.to] = dist[u] + edge.weight; } } } return dist; } const treeDistances = dijkstra(tree, 0); const graphDistances = dijkstra(graph, 0); console.log(JSON.stringify({ treeDistances, graphDistances }));
The tree has a single path from 0 to 2 through 1 with weights 2 and 3, totaling 5. The graph has a shorter path from 0 to 2 directly or via 1 with total weight 3.
type Edge = { to: number; weight: number }; const graph: Edge[][] = [ [{ to: 1, weight: 1 }], [{ to: 0, weight: 1 }, { to: 2, weight: -2 }], [{ to: 1, weight: -2 }] ]; function dijkstra(graph: Edge[][], start: number): number[] { const dist = Array(graph.length).fill(Infinity); dist[start] = 0; const visited = new Set<number>(); while (visited.size < graph.length) { let u = -1; let minDist = Infinity; for (let i = 0; i < dist.length; i++) { if (!visited.has(i) && dist[i] < minDist) { minDist = dist[i]; u = i; } } if (u === -1) break; visited.add(u); for (const edge of graph[u]) { if (dist[u] + edge.weight < dist[edge.to]) { dist[edge.to] = dist[u] + edge.weight; } } } return dist; } console.log(dijkstra(graph, 0));
Dijkstra's algorithm assumes all edge weights are non-negative. Negative weights can cause it to produce incorrect results because it may finalize distances too early.
type Edge = { to: number; weight: number }; const graph: Edge[][] = [ [{ to: 1, weight: 2 }, { to: 2, weight: 3 }], [{ to: 0, weight: 2 }, { to: 2, weight: 4 }], [{ to: 0, weight: 3 }, { to: 1, weight: 4 }] ];
Option A ends the array with a closing parenthesis ')' instead of a closing bracket ']'. This causes a syntax error.
Graphs can have cycles and multiple paths, so shortest path algorithms must carefully track and update distances to avoid incorrect results. Trees have a unique path between nodes, making shortest path simpler.