⬅ Previous Topic
Alien Dictionary Character OrderNext Topic ⮕
Shortest Path in DAG using Topological Sort⬅ Previous Topic
Alien Dictionary Character OrderNext Topic ⮕
Shortest Path in DAG using Topological SortTopic Contents
Given an Undirected Graph with unit weights (i.e., every edge has weight 1), the task is to compute the shortest path from a given source node (assumed to be 0
) to all other nodes in the graph.
If a node is unreachable from the source, return -1
for that node.
distance
with -1
for all nodes.distance[0] = 0
as the source is node 0.queue
and enqueue node 0.current
.current
:distance[neighbor] == -1
, set distance[neighbor] = distance[current] + 1
and enqueue the neighbor.distance
array.function shortestPathUnitWeight(n, edges) {
const graph = Array.from({ length: n }, () => []);
// Build the undirected graph
for (const [u, v] of edges) {
graph[u].push(v);
graph[v].push(u);
}
const distance = new Array(n).fill(-1);
const queue = [0];
distance[0] = 0;
while (queue.length > 0) {
const current = queue.shift();
for (const neighbor of graph[current]) {
if (distance[neighbor] === -1) {
distance[neighbor] = distance[current] + 1;
queue.push(neighbor);
}
}
}
return distance;
}
// Example usage:
console.log("Shortest distances:", shortestPathUnitWeight(4, [[0,1],[0,2],[1,3]])); // Output: [0,1,1,2]
console.log("Disconnected graph:", shortestPathUnitWeight(3, [[0,1]])); // Output: [0,1,-1]
⬅ Previous Topic
Alien Dictionary Character OrderNext Topic ⮕
Shortest Path in DAG using Topological SortYou 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.