leetcode 签到1162. 地图分析
题目
- 地图分析
你现在手里有一份大小为 N x N 的『地图』(网格) grid,上面的每个『区域』(单元格)都用 0 和 1 标记好了。其中 0 代表海洋,1 代表陆地,你知道距离陆地区域最远的海洋区域是是哪一个吗?请返回该海洋区域到离它最近的陆地区域的距离。
我们这里说的距离是『曼哈顿距离』( Manhattan Distance):(x0, y0) 和 (x1, y1) 这两个区域之间的距离是 |x0 - x1| + |y0 - y1| 。
如果我们的地图上只有陆地或者海洋,请返回 -1。
示例 1:

输入:[[1,0,1],[0,0,0],[1,0,1]]
输出:2
解释:
海洋区域 (1, 1) 和所有陆地区域之间的距离都达到最大,最大距离为 2。
示例 2:

输入:[[1,0,0],[0,0,0],[0,0,0]]
输出:4
解释:
海洋区域 (2, 2) 和所有陆地区域之间的距离都达到最大,最大距离为 4。
提示:
1 <= grid.length == grid[0].length <= 100
grid[i][j] 不是 0 就是 1
来源:leetcode
链接:https://leetcode-cn.com/problems/as-far-from-land-as-possible/
思路
大眼一瞅,我的笨方法可以写啊。

不过三重循环。。不会超时吗?

提交一下

果然超时了。。

不着急,赶紧去康题解。大部分都是染色
https://leetcode-cn.com/problems/as-far-from-land-as-possible/solution/pythonbfsjian-dan-yi-dong-by-luanz/
拉过来个代码看看
超时代码
class Solution:
def maxDistance(self, grid):
a=[]
num=0
for i in range(len(grid)):
for j in range(len(grid)):
if grid[i][j]==1:
a.append(i)
a.append(j)
if grid[i][j] == 0:
num+=1
b=[]
if num==pow(len(grid),2):
return -1
for i in range(len(grid)):
for j in range(len(grid)):
if grid[i][j]==0:
k=0
M=100000000
while k+1<len(a):
if abs(a[k]-i)+abs(a[k+1]-j)<M :
M=abs(a[k]-i)+abs(a[k+1]-j)
k += 2
b.append(M)
if len(b)==0:
return -1
return max(b)
代码
class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
nodes = [(i, j) for i in range(m) for j in range(n) if grid[i][j]] #提取陆地坐标列表
if not nodes or len(nodes)==m*n:#是否为纯陆地或纯海洋
return -1
def isValid(x, y):#判断给定坐标是否有效
return 0<= x <m and 0<= y <n
depth = -1
delt = [(0,1),(0,-1),(1,0),(-1,0)]
while nodes:#处理当前层信息
depth += 1
tmp = []#存储待探索海洋坐标
for x, y in nodes:#对当前每个待探坐标分别处理4个方向
for d in delt:
newx, newy = x+d[0], y+d[1]
if isValid(newx, newy) and not grid[newx][newy]:#新点是海洋且未探测
tmp.append((newx, newy))
grid[newx][newy] = 1
nodes = tmp
return depth
作者:luanz
链接:https://leetcode-cn.com/problems/as-far-from-land-as-possible/solution/pythonbfsjian-dan-yi-dong-by-luanz/
路漫漫其修远兮,吾将上下而求索。


浙公网安备 33010602011771号