当前位置:网站首页>【LeetCode】1162-地图分析
【LeetCode】1162-地图分析
2022-07-02 12:09:00 【酥酥~】
你现在手里有一份大小为 n x n 的 网格 grid,上面的每个 单元格 都用 0 和 1 标记好了。其中 0 代表海洋,1 代表陆地。
请你找出一个海洋单元格,这个海洋单元格到离它最近的陆地单元格的距离是最大的,并返回该距离。如果网格上只有陆地或者海洋,请返回 -1。
我们这里说的距离是「曼哈顿距离」( Manhattan Distance):(x0, y0) 和 (x1, y1) 这两个单元格之间的距离是 |x0 - x1| + |y0 - y1| 。
示例 1:

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

输入: grid = [[1,0,0],[0,0,0],[0,0,0]]
输出: 4
解释:
海洋单元格 (2, 2) 和所有陆地单元格之间的距离都达到最大,最大距离为 4。
提示:
- n == grid.length
- n == grid[i].length
- 1 <= n <= 100
- grid[i][j] 不是 0 就是 1
思路:
广度优先遍历,从每一块陆地开始,给所有的能到达的海洋赋值(距离)
#广度优先遍历
class Solution(object):
def maxDistance(self,grid):
n = len(grid)#获取数列大小
for i in range(n):
for j in range(n):
if grid[i][j] == 1:#遇见陆地,开始广度遍历给海洋赋值(即距离)
queue = []
queue.append((i,j))
while queue:
x,y = queue[0]
tmp = grid[x][y]+1
queue.pop(0)
for xx,yy in [(x,y+1),(x,y-1),(x+1,y),(x-1,y)]:
if 0<=xx<n and 0<=yy<n and (grid[xx][yy]==0 or grid[xx][yy]>tmp):
grid[xx][yy] = tmp
queue.append((xx,yy))
result = 0
for k in grid:
result = max(result,max(k))
return result-1 if result!=1 and result!=0 else -1
边栏推荐
- Facing the challenge of "lack of core", how can Feiling provide a stable and strong guarantee for customers' production capacity?
- yolo格式数据集处理(xml转txt)
- Application of CDN in game field
- LeetCode_ String_ Simple_ 412.Fizz Buzz
- Yolov5 code reproduction and server operation
- Summary of the first three passes of sqli Labs
- 数据分析常见的英文缩写(一)
- Bing. Site Internet
- 10_Redis_geospatial_命令
- SQL stored procedure
猜你喜欢

Leetcode skimming -- verifying the preorder serialization of binary tree # 331 # medium

Yolov5 code reproduction and server operation

NBA player analysis

Facing the challenge of "lack of core", how can Feiling provide a stable and strong guarantee for customers' production capacity?

Learn the method code example of converting timestamp to uppercase date using PHP

List集合&UML图

搭载TI AM62x处理器,飞凌FET6254-C核心板首发上市!

Let your HMI have more advantages. Fet-g2ld-c core board is a good choice

05_ queue

Leetcode question brushing - parity linked list 328 medium
随机推荐
Real estate market trend outlook in 2022
4. Data splitting of Flink real-time project
YOLOV5 代码复现以及搭载服务器运行
百变大7座,五菱佳辰产品力出众,人性化大空间,关键价格真香
Leetcode skimming -- sum of two integers 371 medium
[solution] educational codeforces round 82
04_ Stack
做好抗“疫”之路的把关人——基于RK3568的红外热成像体温检测系统
数据分析思维分析方法和业务知识——业务指标
Build your own semantic segmentation platform deeplabv3+
05_ queue
Bing.com网站
List集合&UML图
Redux——详解
LeetCode_ Sliding window_ Medium_ 395. Longest substring with at least k repeated characters
搭建自己的语义分割平台deeplabV3+
Equipped with Ti am62x processor, Feiling fet6254-c core board is launched!
Solution of Queen n problem
18_ Redis_ Redis master-slave replication & cluster building
自定义异常