PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#BS0000439. Đường đi an toàn nhất trên lưới (Find the Safest Path in a Grid)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Đườ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 nn rows and nn columns, numbered from 11 to nn. The value ai,ja_{i,j} is 11 if cell (i,j)(i,j) contains a thief and 00 otherwise. At least one thief is present.

You start at (1,1)(1,1) and must reach (n,n)(n,n). 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 (i,j)(i,j) and (u,v)(u,v) is ∣i−u∣+∣j−v∣|i-u|+|j-v|. 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 (1,1)(1,1) to (n,n)(n,n).

Input

  • The first line contains the integer nn, the number of rows and columns.
  • The next nn lines each contain nn integers; line ii gives ai,1,ai,2,…,ai,na_{i,1},a_{i,2},\ldots,a_{i,n}, the thief locations in row ii.

Output

Print one integer: the greatest safety attainable by a valid route.

Subtasks

  • Subtask 1 (20 points): 1≤n≤201\le n\le 20; ai,j∈{0,1}a_{i,j}\in\{0,1\} for all 1≤i,j≤n1\le i,j\le n; 1≤∑i=1n∑j=1nai,j≤n21\le\sum_{i=1}^n\sum_{j=1}^n a_{i,j}\le n^2.
  • Subtask 2 (30 points): 1≤n≤4001\le n\le 400; ai,j∈{0,1}a_{i,j}\in\{0,1\} for all 1≤i,j≤n1\le i,j\le n; $1\le\sum_{i=1}^n\sum_{j=1}^n a_{i,j}\le \min(10,n^2)$.
  • Subtask 3 (50 points): 1≤n≤4001\le n\le 400; ai,j∈{0,1}a_{i,j}\in\{0,1\} for all 1≤i,j≤n1\le i,j\le n; 1≤∑i=1n∑j=1nai,j≤n21\le\sum_{i=1}^n\sum_{j=1}^n a_{i,j}\le n^2.

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 00 from a thief. Distances are nonnegative, hence the optimum is 00.

Example 2

Input

3
0 0 1
0 0 0
0 0 0

Output

2

Explanation

The thief is at (1,3)(1,3). Along (1,1),(2,1),(3,1),(3,2),(3,3)(1,1),(2,1),(3,1),(3,2),(3,3) the distances are 2,3,4,3,22,3,4,3,2. The score is 22. The starting cell is exactly distance 22 from the thief, ruling out any larger score.

Illustration

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 (1,4)(1,4) and (4,1)(4,1). On route (1,1),(1,2),(2,2),(2,3),(3,3),(3,4),(4,4)(1,1),(1,2),(2,2),(2,3),(3,3),(3,4),(4,4) the nearest-thief distances are 3,2,3,2,3,2,33,2,3,2,3,2,3. For score 33, neither neighbor of the start is allowed because both have distance 22. Thus the optimum is 22.