Description

Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)

A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.

Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves.

Example 1:

Input: [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation:
There are three 1s that are enclosed by 0s, and one 1 that isn't enclosed because its on the boundary.

Example 2:

Input: [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation:
All 1s are either on the boundary or can reach the boundary.

Note:

  1. 1 <= A.length <= 500
  2. 1 <= A[i].length <= 500
  3. 0 <= A[i][j] <= 1
  4. All rows have the same size.

分析

题目的意思是:给定一个矩阵,1代表陆地,0表示海洋;返回网格中无法在任意次数的移动中离开矩阵边界的陆地的数量。这道题一看就是一个dfs的题目,把能到达边界的陆地填上2,剩下的保持1的陆地就是离不开矩阵边界的陆地了,如果能想到这个就好办了。

  • 从边界上的1开始深度优先搜索,把遍历到的1填上2.
  • 遍历矩阵统计1的个数就是答案了。

代码

class Solution:
def dfs(self,A,i,j):
m=len(A)
n=len(A[0])
if(i<0 or i>=m or j<0 or j>=n):
return

if(A[i][j]==1):
A[i][j]=2
self.dfs(A,i-1,j)
self.dfs(A,i+1,j)
self.dfs(A,i,j-1)
self.dfs(A,i,j+1)

def numEnclaves(self, A: List[List[int]]) -> int:
m=len(A)
n=len(A[0])
for i in range(m):
for j in range(n):
if(i==0 or i==m-1 or j==0 or j==n-1):
if(A[i][j]==1):
self.dfs(A,i,j)
res=0
for i in range(m):
for j in range(n):
if(A[i][j]==1):
res+=1
return res

参考文献

[LeetCode] 1020. Number of Enclaves