1020. Number of Enclaves (M)

https://leetcode.com/problems/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 either 0 or 1.

Solution:

Similar as LeetCode 1254

这题不让你求封闭岛屿的数量,而是求封闭岛屿的面积总和。

其实思路都是一样的,先把靠边的陆地淹掉,然后去数剩下的陆地数量就行了.

class Solution {
    public int numEnclaves(int[][] grid) {
        
        int m = grid.length;
        int n = grid[0].length;
        for(int i = 0; i< n; i++)
        {
            dfs(grid, 0, i);
            dfs(grid, m-1, i);
        }
        for(int i = 0; i< m; i++)
        {
            dfs(grid, i, 0);
            dfs(grid,i, n-1);
        }
        int result = 0;
        for(int i = 0; i< m ;i++)
        {
            for(int j = 0; j< n; j++)
            {
                if(grid[i][j] == 1)
                {
                    result++;
                }
            }
        }
        return result;
        
    }
    
    public void dfs(int[][] grid, int x, int y)
    {
        int m = grid.length;
        int n = grid[0].length;
        if(x<0 || y<0 || x>=m || y>=n) return;
        if(grid[x][y] == 0) return;
        grid[x][y] = 0;
        dfs(grid, x-1, y);
        dfs(grid, x+1, y);
        dfs(grid, x, y-1);
        dfs(grid, x, y+1);
    }
}

Last updated

Was this helpful?