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.
飞地的数量。
给你一个大小为 m x n 的二进制矩阵 grid ,其中 0 表示一个海洋单元格、1 表示一个陆地单元格。
publicintnumEnclaves(int[][] grid) { m = grid.length; n = grid[0].length; for (inti=0; i < m; i++) { for (intj=0; j < n; j++) { // 处理边界上的 1 if ((i == 0 || j == 0 || i == m - 1 || j == n - 1) && grid[i][j] == 1) { dfs(grid, i, j); } } }
// 处理不能触及边界的 1 intres=0; for (inti=0; i < m; i++) { for (intj=0; j < n; j++) { if (grid[i][j] == 1) { res++; } } } return res; }
privatevoiddfs(int[][] grid, int i, int j) { if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 0) { return; } grid[i][j] = 0; dfs(grid, i - 1, j); dfs(grid, i + 1, j); dfs(grid, i, j - 1); dfs(grid, i, j + 1); } }