AceYourInterviews
Checking sign-in…

116. 0–1 BFS — Binary Edge Weights

AdvancedDijkstra’s two distance levels implemented with a deque

Find the minimum total edge weight from the source to each declared vertex. Some edges are free to traverse and others cost one.

Minimize total cost rather than the number of edges. Return a separate result for unreachable vertices and preserve the graph's directed relationships.

Example 1

Input

n=4, edges=[[0,1,1],[0,2,0],[2,1,0]], source=0

Output

[0,0,0,−1]

Explanation: The zero-cost two-hop route improves vertex one after its initial cost-one discovery.

Example 2

Input

n=3, edges=[[0,1,0],[1,0,0],[1,2,1]], source=0

Output

[0,0,1]

Explanation: Strict relaxation stops the zero cycle from generating repeated equal entries.

Constraints

  • 1 <= n <= 105
  • 0 <= edge occurrences <= 2 * 105
  • 0 <= vertex label < n
  • edges[i].length == 3
  • 0 <= source < n
  • weight is 0 or 1
Hints
Hint 1

What two costs can a processed distance d propose?

Hint 2

Zero-cost work belongs before pending d+1 work.

Hint 3

Push strict zero improvements to the front, one improvements to the back, and skip stale stored costs.

Related LeetCode practice ↗
Code
Saved on this deviceLn 1, Col 1

Zero detour supersedes a one-cost proposal

4
[[0,1,1],[0,2,0],[2,1,0],[1,2,0]]
0
[0,0,0,-1]