当前位置:网站首页>One question per day 1020 Number of enclaves
One question per day 1020 Number of enclaves
2022-07-05 06:12:00 【A big pigeon】
topic :
Give you a size of m x n The binary matrix of grid , among 0 Represents an ocean cell 、1 Represents a land cell .
once Move It refers to walking from one land cell to another ( On 、 Next 、 Left 、 Right ) Land cells or across grid The boundary of the .
Return to grid unable Land that leaves the grid boundary in any number of movements ( enclave ) The number of cells .
Explain : use 2 Mark the land you can leave .
First mark the outermost land 2. And then from 2 set out , Depth first search the surrounding land is marked 2.
Last grid The unmarked land in is the enclave .
class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
def dfs(i,j):
nonlocal grid,m,n
if i<0 or j<0 or i>=m or j >=n :
return
if grid[i][j]==1:
grid[i][j] = 2 # Departable land
dfs(i+1,j)
dfs(i-1,j)
dfs(i,j-1)
dfs(i,j+1)
return
m, n = len(grid), len(grid[0])
cnt = 0
for i in range(m):
grid[i][0] = 2 if grid[i][0] == 1 else 0
grid[i][n-1] = 2 if grid[i][n-1] == 1 else 0
for j in range(n):
grid[0][j] = 2 if grid[0][j] == 1 else 0
grid[m-1][j] = 2 if grid[m-1][j] == 1 else 0
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
dfs(i+1,j)
dfs(i-1,j)
dfs(i,j-1)
dfs(i,j+1)
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
cnt += 1
return cnt
边栏推荐
猜你喜欢
4. 对象映射 - Mapping.Mapster
Implement an iterative stack
【云原生】微服务之Feign自定义配置的记录
[jailhouse article] look mum, no VM exits
[practical skills] technical management of managers with non-technical background
Wazuh開源主機安全解决方案的簡介與使用體驗
实时时钟 (RTC)
leetcode-6111:螺旋矩阵 IV
Arduino 控制的 RGB LED 无限镜
MatrixDB v4.5.0 重磅发布,全新推出 MARS2 存储引擎!
随机推荐
leetcode-6109:知道秘密的人数
leetcode-6110:网格图中递增路径的数目
Individual game 12
Records of some tools 2022
LeetCode 1200.最小绝对差
js快速将json数据转换为url参数
leetcode-556:下一个更大元素 III
Convolution neural network -- convolution layer
Simply sort out the types of sockets
Leetcode-1200: minimum absolute difference
Navicat连接Oracle数据库报错ORA-28547或ORA-03135
4. 对象映射 - Mapping.Mapster
CPU内核和逻辑处理器的区别
MatrixDB v4.5.0 重磅发布,全新推出 MARS2 存储引擎!
927. Trisection simulation
Spark中groupByKey() 和 reduceByKey() 和combineByKey()
Doing SQL performance optimization is really eye-catching
1039 Course List for Student
In depth analysis of for (VaR I = 0; I < 5; i++) {settimeout (() => console.log (I), 1000)}
[rust notes] 14 set (Part 1)