Minimum Cost to Make at Least One Valid Path in a Grid (LeetCode 1368): Solution and Explanation

Hard
Array
Breadth First Search
Graph
Heap Priority Queue
Matrix
Shortest Path

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

  1. Fill a cost matrix with infinity and set cost[0][0] = 0. Put (0,0) in a deque.
  2. Pop a cell from the front.
  3. For each direction k (right, left, down, up), the weight is 0 if grid[r][c] == k + 1 and 1 otherwise.
  4. If the neighbour is inside the grid and cost[r][c] + w beats its cost, update it and push it to the front when w is 0 or to the back when w is 1.
  5. When the deque is empty, return cost[m-1][n-1].

Step-by-step example

grid = [[1,2],[4,3]]
  1. 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.
  2. 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.
  3. 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.
  4. 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]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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.