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.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 100
  • 1 ≤ grid[i][j] ≤ 4

Visualization

Tap to expand
Minimum Cost Valid Path in Grid INPUT --> --> --> --> <-- <-- <-- <-- --> --> --> --> <-- <-- <-- <-- S E Legend: 1: Right (-->) 2: Left (<--) 3: Down, 4: Up [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]] ALGORITHM (0-1 BFS) 1 Use Deque Cost 0: add to front Cost 1: add to back 2 Start from (0,0) Initial cost = 0 3 For each cell Follow arrow: cost 0 Change arrow: cost 1 4 Track min cost Return cost at (m-1,n-1) BFS Processing Order: 0 0 0 1 2 Numbers = min cost to reach cell FINAL RESULT --> --> --> v v v END Green = Free path (follow arrows) Red = Changed arrows (cost 1 each) Output: 3 OK - 3 arrows changed (at positions (0,3), (1,3), (2,3)) Key Insight: This is a 0-1 BFS problem! Following the current arrow direction has cost 0, while changing it costs 1. Use a deque: add cost-0 moves to front, cost-1 moves to back. This ensures we always process minimum-cost paths first, giving optimal solution in O(m*n) time complexity. TutorialsPoint - Minimum Cost to Make at Least One Valid Path in a Grid | BFS Approach
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