[LeetCode] 1020. Number of Enclaves
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
.
飞地的数量。
给你一个大小为 m x n 的二进制矩阵 grid ,其中 0 表示一个海洋单元格、1 表示一个陆地单元格。
一次 移动 是指从一个陆地单元格走到另一个相邻(上、下、左、右)的陆地单元格或跨过 grid 的边界。
返回网格中 无法 在任意次数的移动中离开网格边界的陆地单元格的数量。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-enclaves
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题意不难理解,就是变相的 flood fill 类型的题目。这里我给出 BFS 和 DFS 两种解法,时间复杂度均为O(mn),空间复杂度均为O(n)。如果代码看不懂,请先移步200题。无论是哪种做法,都需要遍历 matrix 两遍。第一遍先找 matrix 边界上的 1,然后 traverse,并且把遇到的 1 改成一个其他的数字。再一次遍历 matrix,如果 matrix 中还有 1,就说明这些1是无法按规则访问到 matrix 边界并且离开 matrix 的。
BFS
1 class Solution { 2 public int numEnclaves(int[][] A) { 3 int m = A.length; 4 int n = A[0].length; 5 Queue<int[]> queue = new LinkedList<>(); 6 for (int i = 0; i < m; i++) { 7 for (int j = 0; j < n; j++) { 8 if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { 9 if (A[i][j] == 1) { 10 queue.offer(new int[] { i, j }); 11 } 12 } 13 } 14 } 15 16 while (!queue.isEmpty()) { 17 int[] cur = queue.poll(); 18 int x = cur[0]; 19 int y = cur[1]; 20 if (x < 0 || y < 0 || x >= m || y >= n || A[x][y] != 1) { 21 continue; 22 } 23 A[x][y] = 2; 24 queue.offer(new int[] { x - 1, y }); 25 queue.offer(new int[] { x + 1, y }); 26 queue.offer(new int[] { x, y - 1 }); 27 queue.offer(new int[] { x, y + 1 }); 28 } 29 30 int count = 0; 31 for (int i = 0; i < m; i++) { 32 for (int j = 0; j < n; j++) { 33 if (A[i][j] == 1) { 34 count++; 35 } 36 } 37 } 38 return count; 39 } 40 }
DFS
1 class Solution { 2 int m; 3 int n; 4 5 public int numEnclaves(int[][] grid) { 6 m = grid.length; 7 n = grid[0].length; 8 for (int i = 0; i < m; i++) { 9 for (int j = 0; j < n; j++) { 10 // 处理边界上的1 11 if ((i == 0 || i == m - 1 || j == 0 || j == n - 1) && grid[i][j] == 1) { 12 dfs(grid, i, j); 13 } 14 } 15 } 16 17 // 记录内圈有多少个1 18 int count = 0; 19 for (int i = 0; i < m; i++) { 20 for (int j = 0; j < n; j++) { 21 if (grid[i][j] == 1) { 22 count++; 23 } 24 } 25 } 26 return count; 27 } 28 29 private void dfs(int[][] grid, int i, int j) { 30 if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) { 31 return; 32 } 33 grid[i][j] = 0; 34 dfs(grid, i - 1, j); 35 dfs(grid, i + 1, j); 36 dfs(grid, i, j - 1); 37 dfs(grid, i, j + 1); 38 } 39 }