#BS0000421. Thoát khỏi đám cháy lan rộng (Escape the Spreading Fire)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Thoát khỏi đám cháy lan rộng (Escape the Spreading Fire)
Escape the Spreading Fire
Source: LeetCode
Version: Phuoc Hung OJ Extended
Problem Statement
A field has rows and columns, both numbered from . A cell value of means grass, means a cell initially on fire, and means a wall. Adjacency requires a shared edge.
You start at and must reach the safehouse at . Before departure you may wait a nonnegative integer number of minutes at the starting cell. Afterwards, each minute you may move to an adjacent grassy cell that is not yet burning. Neither you nor fire can pass through walls.
In each minute your waiting or movement occurs first. Then fire simultaneously spreads from all burning cells into adjacent non-wall cells. Burning cells remain on fire. You are unsafe if fire reaches your current cell, except when you have just entered the safehouse in that same minute: this counts as a successful escape.
Determine the largest possible waiting time at the starting cell that still allows a safe escape.
Input
The first line contains integers , the number of rows and columns.
Each of the next lines contains exactly integers , describing row from column through column ().
Output
Print one integer, the maximum waiting time; print -1 if immediate departure cannot succeed, or 1000000000 if arbitrarily long waiting is possible.
Subtasks
- Subtask 1 (20 points): ; ; for all ; .
- Subtask 2 (30 points): ; ; for all ; .
- Subtask 3 (50 points): ; ; for all ; .
Examples
Input
5 7
0 2 0 0 0 0 0
0 0 0 2 2 1 0
0 2 0 0 1 2 0
0 0 2 2 2 0 2
0 0 0 0 0 0 0
Output
3
Explanation
Wait three minutes, move down four times and right six times. Reach (4,5) in minute 12, one minute before fire, then enter (4,6) in minute 13. Fire reaches home in minute 14. Its sole grassy neighbor is (4,5), at least nine steps from the start. Waiting four minutes means reaching it no earlier than minute 13, when it burns. Print 3.
Input
3 4
0 0 0 0
0 1 2 0
0 2 0 0
Output
-1
Explanation
Fire starts at (1,1). At the end of minute one, both (0,1) and (1,0) burn. These are the only possible first steps from (0,0), and neither remains safe. Print -1.
Input
3 3
0 0 0
2 2 0
1 2 0
Output
1000000000
Explanation
Fire at (2,0) is completely enclosed by walls at (1,0) and (2,1). The route (0,0), (0,1), (0,2), (1,2), (2,2) never burns. You may wait indefinitely and then take four steps. Print 1000000000.