You are given an m x n
binary matrix grid
, where 0
represents a sea cell and 1
represents a land cell.
(资料图片)
A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid
.
Return the number of land cells in grid
for which we cannot walk off the boundary of the grid in any number of moves.
Example 1:
Input: grid = [[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 is not enclosed because its on the boundary.
Example 2:
Input: grid = [[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.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 500
grid[i][j]
is either 0
or 1
.
Accepted
95,195
Submissions
145,440
DFS 一定要有返回的条件,不然直接就内存溢出了。。。
相当于把边上为1的数字直接改成0,当然包含跟他相邻的数字,
然后再计算剩下1的数量,返回即可。
Runtime: 9 ms, faster than 76.21% of Java online submissions for Number of Enclaves.
Memory Usage: 53.8 MB, less than 76.65% of Java online submissions for Number of Enclaves.
关键词: 内存溢出