DSA Graphs

Minimum Cost to Make at Least One Valid Path in a Grid

0-1 BFS — following the arrow costs 0, changing direction costs 1.

Hard
Time O(m*n) Space O(m*n)
LeetCode
6 min read
bfs dijkstra grid 0-1-bfs

Problem#

Each cell contains an arrow (1=right, 2=left, 3=down, 4=up). You start at the top-left and want to reach the bottom-right. At each step you follow the arrow for free, or you can pay 1 to change the arrow of the current cell, but you can only change each cell once. Return the minimum cost.

Examples#

  • grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]3
  • grid = [[1,1,3],[3,2,2],[1,1,4]]0

Constraints#

  • 1 <= m, n <= 100.

Approach#

0-1 BFS with a deque. From cell (r, c), transitions are: follow the arrow → cost 0 (push to front); choose any other direction → cost 1 (push to back). Stop when reaching (m-1, n-1).

Solution#

Minimum Cost to Make at Least One Valid Path in a Grid
class Solution {
public:
int minCost(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int dx[5] = {0, 0, 0, 1, -1}, dy[5] = {0, 1, -1, 0, 0};
vector<vector<int>> dist(m, vector<int>(n, INT_MAX));
dist[0][0] = 0;
deque<pair<int,int>> dq;
dq.push_front({0, 0});
while (!dq.empty()) {
auto [r, c] = dq.front(); dq.pop_front();
for (int d = 1; d <= 4; ++d) {
int nr = r + dx[d], nc = c + dy[d];
if (nr < 0 || nr >= m || nc < 0 || nc >= n) continue;
int w = (grid[r][c] == d) ? 0 : 1;
int nd = dist[r][c] + w;
if (nd < dist[nr][nc]) {
dist[nr][nc] = nd;
if (w == 0) dq.push_front({nr, nc});
else dq.push_back({nr, nc});
}
}
}
return dist[m - 1][n - 1];
}
};

Editorial#

0-1 BFS is Dijkstra restricted to weights {0, 1} — the deque keeps two ordered layers without a heap. Pushing 0-weight moves to the front and 1-weight moves to the back maintains a non-decreasing distance order on the deque, the BFS-equivalent invariant.

Complexity#

  • Time: O(m*n).
  • Space: O(m*n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.