09. Minimum Cost to Make at Least One Valid Path in a Grid
Given an $m \times n$ grid where each cell has a sign pointing right, left, down, or up, return the minimum cost to make at least one valid path from (0,0) to (m-1,n-1).
How It Works & Algorithmic Design
Solves using 0-1 BFS with Double-Ended Queue (Deque):
- Distance Matrix: Maintain
cost[r][c]initialized toInfinity. Setcost[0][0] = 0. - Deque Logic:
- If moving in cell's existing sign direction: weight 0 $\to$ push neighbor to FRONT of Deque.
- If changing cell sign direction: weight 1 $\to$ push neighbor to BACK of Deque.
- Return:
cost[m-1][n-1]when destination is popped.
Why This Approach Works Best
0-1 BFS evaluates shortest paths with 0 and 1 edge weights in optimal linear $O(m \times n)$ time without $O(V \log V)$ Dijkstra overhead.
Example Walkthrough
[[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
Grid with direction arrows.
Changing 3 arrows gives valid path to end.
3 total direction changes required.
3
Minimum modification cost.
Answer: Minimum Cost Grid Path 0-1 BFS implementation
function minCost(grid) {
const m = grid.length, n = grid[0].length;
const cost = Array.from({ length: m }, () => new Array(n).fill(Infinity));
cost[0][0] = 0;
const deque = [[0, 0]];
const dirs = [[0,1],[0,-1],[1,0],[-1,0]]; // 1:right, 2:left, 3:down, 4:up
while (deque.length) {
const [r, c] = deque.shift();
if (r === m - 1 && c === n - 1) return cost[r][c];
for (let i = 0; i < 4; i++) {
const nr = r + dirs[i][0], nc = c + dirs[i][1];
if (nr >= 0 && nc >= 0 && nr < m && nc < n) {
const w = (grid[r][c] === i + 1) ? 0 : 1;
if (cost[r][c] + w < cost[nr][nc]) {
cost[nr][nc] = cost[r][c] + w;
if (w === 0) deque.unshift([nr, nc]);
else deque.push([nr, nc]);
}
}
}
}
return cost[m - 1][n - 1];
}Process zero-cost direction steps before one-cost direction changes using a double-ended queue.
0-cost edges get prepended (
unshift/addFirst); 1-cost edges get appended (push/addLast).Optimal linear $O(m \times n)$ algorithm for graphs with binary edge weights.
Avoids PriorityQueue $O(V \log V)$ overhead.