Minimum Cost to Make at Least One Valid Path in a Grid
Hard
Topics
Each cell of the grid holds a sign pointing to the next cell you move to: 1 = right, 2 = left, 3 = down, 4 = up. Starting at the top-left cell, you follow signs for free, but you may change the sign of any cell (cost 1 each). Return the minimum total cost to reach the bottom-right cell.
Example 1
Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]] Output: 3
Example 2
Input: grid = [[1,1,3],[3,2,2],[1,1,4]] Output: 0
Example 3
Input: grid = [[1,2],[4,3]] Output: 1
Constraints
- 1 <= m, n <= 100
- 1 <= grid[i][j] <= 4.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Each cell has an outgoing arrow that is free to follow, and any of the other three directions costs exactly one sign change. So this is a shortest-path problem on a grid where every edge weighs 0 or 1 — and that specific weight set is what makes a priority queue unnecessary.
0-1 BFS replaces the heap with a double-ended queue. A zero-cost move keeps the distance unchanged, so the neighbour belongs at the front alongside the current frontier; a cost-one move belongs at the back, one layer out. The deque therefore stays sorted by distance with at most two distinct values in it, which gives Dijkstra's guarantee at BFS's cost.
Approach
- Initialise all distances to infinity except the top-left, which is 0, and seed the deque with it.
- Pop from the front. For each of the four directions, compute the cost: 0 if the cell's own sign points that way, otherwise 1.
- If that improves the neighbour's distance, record it and push to the front on cost 0 or the back on cost 1.
- The answer is the distance to the bottom-right cell.
Dry Run
grid 1 1 1 1 1 = right, 2 = left, 3 = down, 4 = up
2 2 2 2
1 1 1 1
2 2 2 2
row 0 points right, row 1 points left, and so on -- a snake that never
descends. Each row transition needs one sign change.
reach (0,3) for free by following row 0's arrows cost 0
change (0,3) to point down cost 1
follow row 1 leftward to (1,0) for free cost 1
change (1,0) to point down cost 2
follow row 2 rightward to (2,3) for free cost 2
change (2,3) to point down cost 3
follow row 3 leftward to (3,0)... but the target is (3,3)
the cheapest route reaches the bottom-right with 3 changes
answer 3Complexity
- Time — O(m·n): each cell is relaxed a bounded number of times and each has four edges, so the work is linear in the grid. Dijkstra on the same graph would be O(m·n log(m·n)) — correct, just unnecessary.
- Space — O(m·n) for the distance grid and the deque.
Common Pitfalls
- Using a plain queue. Ordinary BFS assumes every edge costs the same; here following an arrow is free, so a zero-cost neighbour must jump ahead of the cost-one cells already queued.
- Pushing zero-cost neighbours to the back. That is the same bug with the opposite symptom: the deque stops being sorted by distance and the first arrival at a cell is no longer the cheapest.
- Marking cells visited on first touch and never revisiting. With mixed edge weights a cell can be reached more cheaply later, so the test must be on the distance improving, not on a visited flag.
- Treating the arrow as a constraint rather than a discount. You may always move in any of the four directions; the arrow only decides whether it is free.
- Charging for the final cell's sign. Arriving at the bottom-right ends the journey, so its own arrow is never followed and never needs changing.
- Forgetting the 1×1 grid, where the start is already the target and the answer is 0.
Full Solution — all languages
class Solution:
def minCost(self, grid):
from collections import deque
R = len(grid); C = len(grid[0])
INF = float('inf')
dist = [[INF] * C for _ in range(R)]; dist[0][0] = 0
dq = deque([(0, 0)])
dv = ((1, 0, 1), (2, 0, -1), (3, 1, 0), (4, -1, 0))
while dq:
r, c = dq.popleft()
for v, dr, dc in dv:
nr, nc = r + dr, c + dc
if nr < 0 or nr >= R or nc < 0 or nc >= C: continue
cost = 0 if grid[r][c] == v else 1
if dist[r][c] + cost < dist[nr][nc]:
dist[nr][nc] = dist[r][c] + cost
if cost == 0: dq.appendleft((nr, nc))
else: dq.append((nr, nc))
return dist[R - 1][C - 1]import java.util.*;
class Solution {
public int minCost(int[][] grid) {
int R = grid.length, C = grid[0].length;
int[][] dist = new int[R][C];
for (int[] row : dist) Arrays.fill(row, Integer.MAX_VALUE);
dist[0][0] = 0;
Deque<int[]> dq = new ArrayDeque<>();
dq.add(new int[]{0, 0});
int[][] dv = { {
1,0,1
},
{
2,0,-1
},
{
3,1,0
},
{
4,-1,0
}
};
while (!dq.isEmpty()) {
int[] cur = dq.pollFirst();
int r = cur[0], c = cur[1];
for (int[] d : dv) {
int v = d[0], nr = r + d[1], nc = c + d[2];
if (nr < 0 || nr >= R || nc < 0 || nc >= C) continue;
int cost = (grid[r][c] == v) ? 0 : 1;
if (dist[r][c] + cost < dist[nr][nc]) {
dist[nr][nc] = dist[r][c] + cost;
if (cost == 0) dq.addFirst(new int[]{nr, nc});
else dq.addLast(new int[]{nr, nc});
}
}
}
return dist[R - 1][C - 1];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int minCost(vector<vector<int>>& grid) {
int R = grid.size(), C = grid[0].size();
const int INF = 1e9;
vector<vector<int>> dist(R, vector<int>(C, INF));
dist[0][0] = 0;
deque<pair<int,int>> dq;
dq.push_back({0, 0});
int dv[4][3] = { {
1,0,1
},
{
2,0,-1
},
{
3,1,0
},
{
4,-1,0
}
};
while (!dq.empty()) {
auto cur = dq.front();
dq.pop_front();
int r = cur.first, c = cur.second;
for (int k = 0; k < 4; k++) {
int v = dv[k][0], nr = r + dv[k][1], nc = c + dv[k][2];
if (nr < 0 || nr >= R || nc < 0 || nc >= C) continue;
int cost = (grid[r][c] == v) ? 0 : 1;
if (dist[r][c] + cost < dist[nr][nc]) {
dist[nr][nc] = dist[r][c] + cost;
if (cost == 0) dq.push_front({nr, nc});
else dq.push_back({nr, nc});
}
}
}
return dist[R - 1][C - 1];
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var minCost = function(grid) {
const R = grid.length, C = grid[0].length, INF = Infinity;
const dist = Array.from({ length: R }, () => new Array(C).fill(INF));
dist[0][0] = 0;
const dq = [[0, 0]];
const dv = [[1, 0, 1], [2, 0, -1], [3, 1, 0], [4, -1, 0]];
while (dq.length) {
const [r, c] = dq.shift();
for (const [v, dr, dc] of dv) {
const nr = r + dr, nc = c + dc;
if (nr < 0 || nr >= R || nc < 0 || nc >= C) continue;
const cost = (grid[r][c] === v) ? 0 : 1;
if (dist[r][c] + cost < dist[nr][nc]) {
dist[nr][nc] = dist[r][c] + cost;
if (cost === 0) dq.unshift([nr, nc]);
else dq.push([nr, nc]);
}
}
}
return dist[R - 1][C - 1];
};