ID | Title | Difficulty | |
---|---|---|---|
Loading... |
1020. Number of Enclaves
Medium
LeetCode
Array, Depth-First Search, Breadth-First Search, Union Find, Matrix
Problem
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 either0
or1
.
Code
class Solution {
int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public int numEnclaves(int[][] grid) {
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
if(i == 0 || j == 0 || i == grid.length - 1 || j == grid[i].length - 1) {
dfs(grid, i, j);
}
}
}
int res = 0;
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
if(grid[i][j] == 1) {
res++;
}
}
}
return res;
}
private void dfs(int[][] grid, int x, int y) {
if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] == 0) return;
grid[x][y] = 0;
for(int[] dir : dirs) {
dfs(grid, x + dir[0], y + dir[1]);
}
}
}
按 <- 键看上一题!
1019. Next Greater Node In Linked List
按 -> 键看下一题!
1027. Longest Arithmetic Subsequence