Minimum Cost to Make at Least One Valid Path in a Grid - Problem

Imagine you're navigating through a maze where each cell has a directional arrow that tells you which direction to move next. Your goal is to find the minimum cost to reach from the top-left corner (0, 0) to the bottom-right corner (m-1, n-1).

Each cell contains one of four directional signs:

  • 1 → Move right (to the next column)
  • 2 → Move left (to the previous column)
  • 3 → Move down (to the next row)
  • 4 → Move up (to the previous row)

The challenge is that some arrows might point in the wrong direction or even outside the grid! You can change any arrow's direction for a cost of 1, but you can only change each arrow once.

Your task is to find the minimum number of arrow changes needed to create at least one valid path from start to finish.

Input & Output

example_1.py — Basic Grid
$ Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
Output: 3
💡 Note: We need to change 3 arrows to create a valid path. One possible solution: change grid[1][1] from 2→1, grid[2][1] from 1→3, and grid[2][2] from 1→3 to create a path that goes right-right-right-down-down-down-right.
example_2.py — Small Grid
$ Input: grid = [[1,1,3],[3,2,2],[1,1,1]]
Output: 0
💡 Note: Following the existing arrows creates a valid path: (0,0)→(0,1)→(0,2)→(1,2)→(2,2), so no changes are needed.
example_3.py — Single Cell
$ Input: grid = [[1]]
Output: 0
💡 Note: We're already at the destination, so no cost is needed.

Visualization

Tap to expand
STARTENDFREE$1FREEJourney Cost🚗 Follow sign: $0🔧 Fix sign: $1Total cost: $1Using 0-1 BFS findsoptimal route efficiently🎯 Key Insight: Model as shortest path with 0-1 edge weights
Understanding the Visualization
1
Start Journey
Begin at top-left intersection with $0 cost
2
Follow or Fix Signs
Follow correct signs for free, or pay $1 to change wrong ones
3
Use Smart Search
0-1 BFS ensures we explore cheapest routes first
4
Reach Destination
First arrival at bottom-right gives minimum cost
Key Takeaway
🎯 Key Insight: This problem is essentially finding the shortest path where following existing arrows costs 0 and changing directions costs 1. The 0-1 BFS approach guarantees optimal solution in O(m×n) time.

Time & Space Complexity

Time Complexity
⏱️
O(m*n)

Each cell is processed at most once, and we examine 4 directions per cell

n
2n
Linear Growth
Space Complexity
O(m*n)

Space for the deque and distance array

n
2n
Linearithmic Space

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 100
  • 1 ≤ grid[i][j] ≤ 4
Asked in
Google 45 Amazon 38 Meta 25 Microsoft 18
28.4K Views
Medium-High Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen