← 返回 apple 的题目列表Shortest path in a grid (BFS) with blocked/unblocked cells and updates
类型:online_judge
Coding: Shortest Path in a Grid (BFS)
Given an m x n grid with open cells 0 and blocked cells 1, find the shortest number of steps from start S=(sr, sc) to target T=(tr, tc). You can move in 4 directions (up/down/left/right) and cannot leave the grid.
Return the shortest steps, or -1 if unreachable.
I/O
Input: m n, then m rows of 0/1 grid, then sr sc tr tc.
Output: shortest steps or -1.
Constraints
1 <= m,n <= 2000
Single run should be about O(mn).
Follow-up
If cells may be updated from blocked (1) to open (0) dynamically (possibly many updates), how would you optimize for repeated shortest-path queries? Discuss trade-offs between rerunning BFS and incremental/dynamic approaches.
Example
Input
3 3
0 0 0
1 1 0
0 0 0
0 0 2 2
Output
4