Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1020.html

1020. Number of Enclaves (Medium)

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.

Related Topics: Depth-first Search

Solution 1. DFS

// OJ: https://leetcode.com/problems/number-of-enclaves/
// Time: O(MN)
// Space: O(1)
class Solution {
    const int dirs[4][2] = { {0, 1}, {0, -1}, {-1, 0}, {1, 0} };
    int M, N;
    void dfs(vector<vector<int>> &A, int x, int y) {
        if (x < 0 || x >= M || y < 0 || y >= N || !A[x][y]) return;
        A[x][y] = 0;
        for (auto &dir : dirs) dfs(A, x + dir[0], y + dir[1]);
    }
public:
    int numEnclaves(vector<vector<int>>& A) {
        M = A.size(), N = A[0].size();
        int ans = 0;
        for (int i = 0; i < M; ++i) dfs(A, i, 0), dfs(A, i, N - 1);
        for (int i = 0; i < N; ++i) dfs(A, 0, i), dfs(A, M - 1, i);
        for (auto &row : A) {
            for (int n : row) {
                if (n) ++ans;
            }
        }
        return ans;
    }
};

Java

  • class Solution {
        public int numEnclaves(int[][] A) {
            int rows = A.length, columns = A[0].length;
            int[][] grid = new int[rows][columns];
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < columns; j++)
                    grid[i][j] = A[i][j];
            }
            for (int i = 0; i < rows; i++) {
                if (grid[i][0] == 1)
                    breadthFirstSearch(grid, i, 0);
                if (grid[i][columns - 1] == 1)
                    breadthFirstSearch(grid, i, columns - 1);
            }
            for (int i = 0; i < columns; i++) {
                if (grid[0][i] == 1)
                    breadthFirstSearch(grid, 0, i);
                if (grid[rows - 1][i] == 1)
                    breadthFirstSearch(grid, rows - 1, i);
            }
            int enclaves = 0;
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < columns; j++) {
                    if (grid[i][j] == 1)
                        enclaves++;
                }
            }
            return enclaves;
        }
    
        public void breadthFirstSearch(int[][] grid, int row, int column) {
            if (grid[row][column] == 0)
                return;
            int rows = grid.length, columns = grid[0].length;
            int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
            grid[row][column] = 0;
            Queue<int[]> queue = new LinkedList<int[]>();
            queue.offer(new int[]{row, column});
            while (!queue.isEmpty()) {
                int[] cell = queue.poll();
                int curRow = cell[0], curColumn = cell[1];
                for (int[] direction : directions) {
                    int newRow = curRow + direction[0], newColumn = curColumn + direction[1];
                    if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && grid[newRow][newColumn] == 1) {
                        grid[newRow][newColumn] = 0;
                        queue.offer(new int[]{newRow, newColumn});
                    }
                }
            }
        }
    }
    
  • // OJ: https://leetcode.com/problems/number-of-enclaves/
    // Time: O(MN)
    // Space: O(1)
    class Solution {
        const int dirs[4][2] = { {0, 1}, {0, -1}, {-1, 0}, {1, 0} };
        int M, N;
        void dfs(vector<vector<int>> &A, int x, int y) {
            if (x < 0 || x >= M || y < 0 || y >= N || !A[x][y]) return;
            A[x][y] = 0;
            for (auto &dir : dirs) dfs(A, x + dir[0], y + dir[1]);
        }
    public:
        int numEnclaves(vector<vector<int>>& A) {
            M = A.size(), N = A[0].size();
            int ans = 0;
            for (int i = 0; i < M; ++i) dfs(A, i, 0), dfs(A, i, N - 1);
            for (int i = 0; i < N; ++i) dfs(A, 0, i), dfs(A, M - 1, i);
            for (auto &row : A) {
                for (int n : row) {
                    if (n) ++ans;
                }
            }
            return ans;
        }
    };
    
  • class Solution:
        def numEnclaves(self, grid: List[List[int]]) -> int:
            def dfs(i, j):
                grid[i][j] = 0
                for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]:
                    x, y = i + a, j + b
                    if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:
                        dfs(x, y)
    
            m, n = len(grid), len(grid[0])
            for i in range(m):
                for j in range(n):
                    if grid[i][j] == 1 and (i == 0 or i == m - 1 or j == 0 or j == n - 1):
                        dfs(i, j)
            return sum(grid[i][j] for i in range(m) for j in range(n))
    
    ############
    
    class Solution(object):
        def canThreePartsEqualSum(self, A):
            """
            :type A: List[int]
            :rtype: bool
            """
            _sum = sum(A)
            if _sum % 3 != 0:
                return False
            target = _sum / 3
            count = 0
            cursum = 0
            for a in A:
                cursum += a
                if cursum == target:
                    count += 1
                    cursum = 0
            return count >= 3
    

All Problems

All Solutions