当前位置:网站首页>[leetcode] 1162 map analysis
[leetcode] 1162 map analysis
2022-07-02 15:36:00 【Crisp ~】
Now you have a copy of n x n Of grid grid, Each of the above Cell Use both 0 and 1 It's marked . among 0 On behalf of the ocean ,1 Representing land .
Please find an ocean cell , The ocean cell has the largest distance to the nearest land cell , And return the distance . If there's only land or ocean on the grid , Please return -1.
The distance we're talking about here is 「 Manhattan distance 」( Manhattan Distance):(x0, y0) and (x1, y1) The distance between these two cells is |x0 - x1| + |y0 - y1| .
Example 1:
Input : grid = [[1,0,1],[0,0,0],[1,0,1]]
Output : 2
explain :
Ocean cell (1, 1) And the distance between all the land cells reaches the maximum , The maximum distance is 2.
Example 2:
Input : grid = [[1,0,0],[0,0,0],[0,0,0]]
Output : 4
explain :
Ocean cell (2, 2) And the distance between all the land cells reaches the maximum , The maximum distance is 4.
Tips :
- n == grid.length
- n == grid[i].length
- 1 <= n <= 100
- grid[i][j] No 0 Namely 1
Ideas :
Breadth first traversal , Start with every piece of land , Assign values to all accessible oceans ( distance )
# Breadth first traversal
class Solution(object):
def maxDistance(self,grid):
n = len(grid)# Get the size of the sequence
for i in range(n):
for j in range(n):
if grid[i][j] == 1:# Meet land , Start breadth traversal and assign values to the ocean ( Distance )
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
边栏推荐
- Download blender on Alibaba cloud image station
- Steps for Navicat to create a new database
- Case introduction and problem analysis of microservice
- 04. Some thoughts on enterprise application construction after entering cloud native
- 15_Redis_Redis.conf详解
- 【LeetCode】200-岛屿数量
- Pytorch 保存tensor到.mat文件
- 06_ Stack and queue conversion
- 17_Redis_Redis发布订阅
- XML Configuration File
猜你喜欢
随机推荐
04.进入云原生后的企业级应用构建的一些思考
怎样从微信返回的json字符串中截取某个key的值?
[leetcode] 1254 - count the number of closed Islands
Leetcode question brushing - parity linked list 328 medium
03_ Linear table_ Linked list
16_ Redis_ Redis persistence
Engineer evaluation | rk3568 development board hands-on test
【LeetCode】19-删除链表的倒数第N个结点
搭建自己的语义分割平台deeplabV3+
LeetCode刷题——递增的三元子序列#334#Medium
13_ Redis_ affair
Leetcode skimming -- sum of two integers 371 medium
工程师评测 | RK3568开发板上手测试
【LeetCode】1162-地图分析
03. Preliminary use of golang
语义分割学习笔记(一)
[leetcode] 977 square of ordered array
05_ queue
How to intercept the value of a key from the JSON string returned by wechat?
Loss function and positive and negative sample allocation: Yolo series