• Courses
  • Tutorials
  • Interview Prep
Switch to Dark Mode

Shortest Path in a Binary Weight Graph

Last Updated : 22 Jan, 2026

Given an undirected graph with N vertices (numbered from 0 to N-1), where each edge has a weight of either 0 or 1, and a source vertex. Find the shortest paths from the source vertex to all other vertices in the graph.

Example: 

Input: N= 9, Source = 0, Edges: [ [0, 1, 0], [0, 7, 1], [1, 2, 1], [1, 7, 1], [2, 3, 0], [2, 5, 0], [2, 8, 1], [3, 4, 1], [3, 5, 1], [4, 5, 1], [5, 6, 1], [6, 7, 1], [7, 8, 1] ]

Output: [0, 0, 1, 1, 2, 1, 2, 1, 2]

source-0-1-bfs

[Naive Approach] Using Dijkstra Algorithm - O(E x log (V)) Time and O(V) Space

One Approach would be to use Dijkstra's Algorithm to find the shortest distance from a given source node to all other nodes in the graph. The source node's distance from itself is initialized to zero. From there, we iteratively pick the unprocessed node with the minimum distance from the source, this is where a min-heap or a set is typically used for efficiency.

[Expected Approach] Using Deque - O(V + E) time and O(V + E) space

To solve this problem efficiently, we can use 0-1 BFS, which employs a deque to maintain sorted distances in O(V + E) time. By pushing 0-weight edges to the front for immediate processing and 1-weight edges to the back, we can replicate Dijkstra’s priority logic without the computational overhead of a heap.

C++
Java Python C# JavaScript

Output
0 0 1 1 2 1 2 1 2 
Comment