Medium
,Array
,DP
,BFS
,Matrix
1162. As Far from Land as Possible
Given an n x n
grid
containing only values 0
and 1
, where 0
represents water and 1
represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1
.
The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0)
and (x1, y1)
is |x0 - x1|
+ |y0 - y1|
.
Example 1:
Example 2:
Constraints:
n
== grid.length
n
== grid[i].length
n
<= 100grid[i][j]
is 0
or 1
從每個陸地出發,往水域走,做BFS紀錄距離,更新整個grid
,最後取最大的。
MarsgoatFeb 10, 2023
Yen-Chi ChenFri, Feb 10, 2023
這種沒有牆組隔的擴散問題,用DP直接先一輪往右、往下走一遍,再一輪往左、往上走一遍,就可以得到了。
Yen-Chi ChenFri, Feb 10, 2023
Time:
Extra Space:
XD Feb 10, 2023