Minimum Cost to Make at Least One Valid Path in a Grid (LeetCode 1368): Solution and Explanation
Every cell points right, left, down or up. Changing a cell's sign costs 1. Find the cheapest set of changes so that following the signs from the top-left cell reaches the bottom-right cell.
Intuition
Think of each cell as a node with an edge to each of its four neighbours. Leaving a cell in the direction its sign points costs nothing. Leaving in any other direction means changing the sign first, which costs 1.
Now the question is a shortest path from (0,0) to (m-1,n-1) in a graph where every edge weighs 0 or 1. A cell's sign is changed at most once on a cheapest path, so the one-change rule never matters.
Dijkstra would work, but with only two weights a deque is enough. Push a neighbour reached for free onto the front, because it costs the same as the cell just popped. Push a neighbour reached by paying onto the back, because it costs one more.
The deque then always holds costs in non-decreasing order, with at most two distinct values, so cells come out in cost order exactly as they would from a heap.
Approach: 0-1 BFS
- Fill a cost matrix with infinity and set
cost[0][0] = 0. Put (0,0) in a deque. - Pop a cell from the front.
- For each direction k (right, left, down, up), the weight is 0 if
grid[r][c] == k + 1and 1 otherwise. - If the neighbour is inside the grid and
cost[r][c] + wbeats its cost, update it and push it to the front when w is 0 or to the back when w is 1. - When the deque is empty, return
cost[m-1][n-1].
Step-by-step example
grid = [[1,2],[4,3]]
- Start at (0,0) with cost 0. Its sign points right, so (0,1) is reached for 0 and goes to the front. Going down to (1,0) costs 1 and goes to the back.
- Pop (0,1) at cost 0. Its sign points left, back to (0,0), which is no improvement. Going down to (1,1) costs 1 and goes to the back.
- Pop (1,0) at cost 1. Its sign points up to (0,0), no improvement. Going right to (1,1) would cost 2, which is worse than 1.
- Pop (1,1) at cost 1. Nothing improves, the deque empties, and the answer is 1: change (0,1) to point down.
Code: Python, Java, C++
1class Solution:
2 def minCost(self, grid: List[List[int]]) -> int:
3 m, n = len(grid), len(grid[0])
4 dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]
5 cost = [[float('inf')] * n for _ in range(m)]
6 cost[0][0] = 0
7 dq = deque([(0, 0)])
8 while dq:
9 r, c = dq.popleft()
10 for k, (dr, dc) in enumerate(dirs):
11 nr, nc = r + dr, c + dc
12 w = 0 if grid[r][c] == k + 1 else 1
13 if 0 <= nr < m and 0 <= nc < n and cost[r][c] + w < cost[nr][nc]:
14 cost[nr][nc] = cost[r][c] + w
15 if w == 0:
16 dq.appendleft((nr, nc))
17 else:
18 dq.append((nr, nc))
19 return cost[m - 1][n - 1]1class Solution {
2 public int minCost(int[][] grid) {
3 int m = grid.length, n = grid[0].length;
4 int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
5 int[][] cost = new int[m][n];
6 for (int[] row : cost) Arrays.fill(row, Integer.MAX_VALUE);
7 cost[0][0] = 0;
8 Deque<int[]> dq = new ArrayDeque<>();
9 dq.offerFirst(new int[]{0, 0});
10 while (!dq.isEmpty()) {
11 int[] cur = dq.pollFirst();
12 int r = cur[0], c = cur[1];
13 for (int k = 0; k < 4; k++) {
14 int nr = r + dirs[k][0], nc = c + dirs[k][1];
15 int w = grid[r][c] == k + 1 ? 0 : 1;
16 if (nr >= 0 && nr < m && nc >= 0 && nc < n && cost[r][c] + w < cost[nr][nc]) {
17 cost[nr][nc] = cost[r][c] + w;
18 if (w == 0) dq.offerFirst(new int[]{nr, nc});
19 else dq.offerLast(new int[]{nr, nc});
20 }
21 }
22 }
23 return cost[m - 1][n - 1];
24 }
25}1class Solution {
2public:
3 int minCost(vector<vector<int>>& grid) {
4 int m = grid.size(), n = grid[0].size();
5 int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
6 vector<vector<int>> cost(m, vector<int>(n, INT_MAX));
7 cost[0][0] = 0;
8 deque<pair<int, int>> dq;
9 dq.push_front({0, 0});
10 while (!dq.empty()) {
11 auto [r, c] = dq.front();
12 dq.pop_front();
13 for (int k = 0; k < 4; k++) {
14 int nr = r + dirs[k][0], nc = c + dirs[k][1];
15 int w = grid[r][c] == k + 1 ? 0 : 1;
16 if (nr >= 0 && nr < m && nc >= 0 && nc < n && cost[r][c] + w < cost[nr][nc]) {
17 cost[nr][nc] = cost[r][c] + w;
18 if (w == 0) dq.push_front({nr, nc});
19 else dq.push_back({nr, nc});
20 }
21 }
22 }
23 return cost[m - 1][n - 1];
24 }
25};Time and space complexity
O(m * n)
Costs only decrease and stay between 0 and m + n, and the deque order makes each cell settle almost immediately, so every cell is processed a constant number of times with four neighbour checks.
O(m * n)
The cost matrix and the deque each hold up to m * n entries.
Other approaches
Dijkstra with a binary heap (time O(m * n * log(m * n)), space O(m * n))
Treat it as a general weighted shortest path. Correct and simple, but the heap adds a log factor that the 0/1 weights make unnecessary.
Layered DFS plus BFS (time O(m * n), space O(m * n))
From every cell at cost k, follow signs with DFS to mark all cells reachable for free, then expand one step in every direction to form layer k + 1. It is the same 0-1 idea organised by cost level.
Common mistakes
- Mixing up the sign numbering. 1 is right, 2 is left, 3 is down and 4 is up, so the direction array must be in exactly that order.
- Pushing free moves to the back. Then the deque is no longer sorted by cost and the result can be too large.
- Using a visited set that blocks a cell after its first push. A cell first reached by paying can later be reached for free, so compare costs instead.
- Worrying about the change-once rule. A cheapest path never visits a cell twice, so it never needs to change the same sign twice.
Frequently asked questions
Why is 0-1 BFS correct here?
Pushing a 0-weight neighbour to the front and a 1-weight neighbour to the back keeps the deque sorted by cost, so cells leave the deque in the same order Dijkstra's heap would produce.
What if a sign points outside the grid?
That edge simply does not exist. The cell can still leave in any other direction at cost 1.
What is the answer for a 1 x 1 grid?
0. The start is already the bottom-right cell.
What is the time complexity?
O(m * n) time and space with 0-1 BFS, compared with O(m * n * log(m * n)) for Dijkstra with a heap.