#BS0000439. Đường đi an toàn nhất trên lưới (Find the Safest Path in a Grid)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Đường đi an toàn nhất trên lưới (Find the Safest Path in a Grid)
Find the Safest Path in a Grid
Source: LeetCode
Version: Phuoc Hung OJ Extended
Problem Statement
A square region has rows and columns, numbered from to . The value is if cell contains a thief and otherwise. At least one thief is present.
You start at and must reach . Each move may enter a cell sharing a side with the current cell, in one of the four directions, including a cell containing a thief. You must remain within the grid.
The Manhattan distance between and is . A cell's safety is its minimum Manhattan distance to a cell containing a thief. A route's safety is the minimum safety among all cells it visits, including both endpoints.
Find the greatest safety attainable by any route from to .
Input
- The first line contains the integer , the number of rows and columns.
- The next lines each contain integers; line gives , the thief locations in row .
Output
Print one integer: the greatest safety attainable by a valid route.
Subtasks
- Subtask 1 (20 points): ; for all ; .
- Subtask 2 (30 points): ; for all ; $1\le\sum_{i=1}^n\sum_{j=1}^n a_{i,j}\le \min(10,n^2)$.
- Subtask 3 (50 points): ; for all ; .
Examples
Example 1
Input
3
1 0 0
0 0 0
0 0 1
Output
0
Explanation
Both endpoints contain thieves, so every route has a cell at distance from a thief. Distances are nonnegative, hence the optimum is .
Example 2
Input
3
0 0 1
0 0 0
0 0 0
Output
2
Explanation
The thief is at . Along the distances are . The score is . The starting cell is exactly distance from the thief, ruling out any larger score.

Example 3
Input
4
0 0 0 1
0 0 0 0
0 0 0 0
1 0 0 0
Output
2
Explanation
The thieves occupy and . On route the nearest-thief distances are . For score , neither neighbor of the start is allowed because both have distance . Thus the optimum is .