We have a grid where every cell has an arrow pointing in one of four directions: right, left, down, or up. Starting at the top-left corner, we want to reach the bottom-right corner by following arrows. If a cell's arrow already points in the direction we want to travel, moving there is free. If we need to go in a different direction, we pay a cost of 1 to change that cell's arrow.
This is a shortest path problem, but the edge weights are not all the same. Moving to a neighbor that the arrow already points to costs 0. Moving to any other neighbor costs 1. Every edge in this implicit graph has a weight of either 0 or 1.
When edge weights are restricted to 0 and 1, a full Dijkstra with a priority queue is more than the problem needs. A faster approach called 0-1 BFS uses a deque instead.
1 <= m, n <= 100 → The grid has at most 10,000 cells, small enough for both a Dijkstra-based and a BFS-based solution.1 <= grid[i][j] <= 4 → Every cell has exactly one arrow. There are no empty cells or special values to handle.Model the grid as a weighted graph and find the shortest path. Each cell is a node. From each cell, you can move to any of its four in-bounds neighbors. If the cell's arrow already points toward that neighbor, the edge weight is 0. Otherwise, the edge weight is 1.
Dijkstra's algorithm finds shortest paths in graphs with non-negative edge weights. A min-heap (priority queue) always processes the cell with the smallest known cost first, which guarantees that the first time a cell is popped, its recorded distance is final.
dist matrix of size m x n, initialized to infinity. Set dist[0][0] = 0.(0, 0, 0) onto a min-heap, where the first value is cost.dist[m-1][n-1].Loading animation...
The priority queue adds a logarithmic factor on every insert and extract. Because edge weights here are only 0 or 1, a deque removes that overhead.
Since every edge weight is either 0 or 1, Dijkstra's priority queue can be replaced with a deque (double-ended queue):
This processes cells in non-decreasing order of cost, the same order Dijkstra produces, but without the logarithmic overhead of a heap. This technique is 0-1 BFS, and it applies to any shortest path problem whose edge weights are restricted to 0 and 1.
The deque acts as a two-level bucket queue. At any moment it holds cells at cost k near the front and cells at cost k+1 near the back, so the costs along the deque never decrease from front to back. Following a 0-cost edge gives the neighbor the same cost as the current cell, so it joins the front with the other cost-k cells. Following a 1-cost edge gives the neighbor cost k+1, so it goes to the back. Popping from the front therefore always returns a cell with the smallest current cost, which is why the first pop of a cell fixes its final distance.
dist matrix of size m x n, initialized to infinity. Set dist[0][0] = 0.(0, 0) to it.dist[m-1][n-1].Loading animation...