Minimum Cost to Make at Least One Valid Path in a Grid Problem
Description
LeetCode Problem 1368.
Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be:
1which means go to the cell to the right. (i.e go fromgrid[i][j]togrid[i][j + 1])2which means go to the cell to the left. (i.e go fromgrid[i][j]togrid[i][j - 1])3which means go to the lower cell. (i.e go fromgrid[i][j]togrid[i + 1][j])4which means go to the upper cell. (i.e go fromgrid[i][j]togrid[i - 1][j])
Notice that there could be some signs on the cells of the grid that point outside the grid.
You will initially start at the upper left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path does not have to be the shortest.
You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.
Return the minimum cost to make the grid have at least one valid path.
Example 1:

Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
Output: 3
Explanation: You will start at point (0, 0).
The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)
The total cost = 3.
Example 2:

Input: grid = [[1,1,3],[3,2,2],[1,1,4]]
Output: 0
Explanation: You can follow the path from (0, 0) to (2, 2).
Example 3:

Input: grid = [[1,2],[4,3]]
Output: 1
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 1001 <= grid[i][j] <= 4
Solution
Approach: 0-1 BFS
Think of the grid as a graph. From each cell you can step to any of its (up to) four neighbors:
- stepping where the sign points is free (cost 0);
- stepping anywhere else means changing this cell's sign first (cost 1).
The answer is the cheapest path from (0, 0) to (m - 1, n - 1) in this graph. The "change a sign at most once" rule never gets in the way: a cheapest path never visits a cell twice, so it never needs to change the same sign twice.
With costs that are only 0 and 1, Dijkstra's algorithm can run with a deque instead of a priority queue (0-1 BFS). Keep dist for every cell, starting with dist[0][0] = 0, and repeat:
- Take the cell at the front of the deque. If it has already been expanded, skip it (it is an older entry with a worse cost).
- For each neighbor, if
dist[cell] + costbeats the neighbor'sdist, update it, and push the neighbor to the front when the cost is 0, or to the back when it is 1.
This keeps the deque sorted by distance, with only two distinct values in it at any time (some d and d + 1), so cells come off the front in order of their final distance, as in Dijkstra. When the loop ends, dist[m - 1][n - 1] is the answer.
In Example 3, [[1,2],[4,3]]: (0, 0) points right to (0, 1) for free, but (0, 1) points back left. Changing it to point down costs 1 and reaches (1, 1), so the answer is 1.
Python, Java and C++ have a deque. In JavaScript and Go, a ring buffer of size 4mn + 1 serves as one: every cell is expanded once and pushes at most 4 entries.
Complexity: O(mn) time, since each cell is expanded once and has 4 neighbors, and O(mn) space for the distances and the deque.
from collections import deque
class Solution:
def minCost(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
moves = [(0, 1), (0, -1), (1, 0), (-1, 0)] # signs 1, 2, 3, 4
dist = [[float("inf")] * n for _ in range(m)] # fewest changes to reach each cell
done = [[False] * n for _ in range(m)]
dist[0][0] = 0
queue = deque([(0, 0)])
while queue:
i, j = queue.popleft()
if done[i][j]:
continue # an older, worse entry for this cell
done[i][j] = True
for sign, (di, dj) in enumerate(moves, 1):
x, y = i + di, j + dj
if 0 <= x < m and 0 <= y < n:
cost = 0 if grid[i][j] == sign else 1 # follow the sign for free, or change it
if dist[i][j] + cost < dist[x][y]:
dist[x][y] = dist[i][j] + cost
if cost == 0:
queue.appendleft((x, y))
else:
queue.append((x, y))
return dist[m - 1][n - 1]