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
Visualization
Time & Space Complexity
Each cell is processed at most once, and we examine 4 directions per cell
Space for the deque and distance array
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 100
- 1 ≤ grid[i][j] ≤ 4