1020 - Number Of Enclaves

#medium

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.

  • 題目的意思: 1不能到邊界,1被0封閉的個數。
class Solution {
public:

    bool dfs( vector<vector<int>> & grid, int m, int n, int i, int j, int & nums ) {
        if ( i < 0 || i >= m || j < 0 || j >= n ) return false;
        if ( grid[i][j] == 0 ) return true;

        grid[i][j] = 0;
        bool up = dfs( grid, m, n, i - 1, j, nums );
        bool down = dfs( grid, m, n, i + 1, j, nums );
        bool left = dfs( grid, m, n, i, j - 1, nums );
        bool right = dfs( grid, m, n, i, j + 1, nums );
        nums++;
        return up && down && left && right;
    }

    int numEnclaves(vector<vector<int>>& grid) {
        int result = 0;
        int m = grid.size();
        int n = grid[0].size();
        int nums = 0;
        for ( int i = 0; i < m; i++ ) {
            for ( int j = 0; j < n; j++ ) {
                nums = 0;
                if ( grid[i][j] == 1 && dfs( grid, m, n, i, j, nums) )
                    result += nums;
            }
        }

        return result;
    }
};