Number of Enclaves

Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)

A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.

Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves.

Example 1:

Input: [[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 isn't enclosed because its on the boundary.

Example 2:

Input: [[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.

Note:

  1. 1 <= A.length <= 500

  2. 1 <= A[i].length <= 500

  3. 0 <= A[i][j] <= 1

  4. All rows have the same size.

class Solution {
    public int numEnclaves(int[][] A) {
        if (A.length == 0)
            return 0;
        // Marking boundary land area
        boolean[][] visited = new boolean[A.length][A[0].length];
        for (int i = 0; i < A.length; i++) {
            if (!visited[i][0])
                markerDFS(A, visited, i, 0);
            if (!visited[i][A[0].length - 1])
                markerDFS(A, visited, i, A[0].length - 1);
        }
        for (int j = 0; j < A[0].length; j++) {
            if (!visited[0][j])
                markerDFS(A, visited, 0, j);
            if (!visited[A.length - 1][j])
                markerDFS(A, visited, A.length - 1, j);
        }
        int count = 0;
        for (int i = 1; i < A.length - 1; i++) {
            for (int j = 1; j < A[0].length - 1; j++) {
                if (!visited[i][j] && A[i][j] == 1)
                    count++;
            }
        }
        return count;
    }

    public void markerDFS(int[][] grid, boolean[][] visited, int x, int y) {
        if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && !visited[x][y] && grid[x][y] == 1) {
            visited[x][y] = true;
            markerDFS(grid, visited, x + 1, y);
            markerDFS(grid, visited, x, y + 1);
            markerDFS(grid, visited, x - 1, y);
            markerDFS(grid, visited, x, y - 1);
        }
    }
}

Last updated