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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code