LeetCode 1020: Number of Enclaves Solution

Master LeetCode problem 1020 (Number of Enclaves), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To solve this problem, we can perform a depth-first search (DFS) from the boundary cells of the grid and mark all connected land cells. After completing the DFS, we can iterate through the grid and count the remaining land cells that were not marked.

  • Perform DFS from boundary cells to mark all connected cells.
  • Count remaining unmarked land cells.

Time complexity: O(m * n) where m is the number of rows and n is the number of columns in the grid. Space complexity: O(m * n) for the recursion stack.

Solution Code

class Solution {
    public int numEnclaves(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;

        for (int i = 0; i < m; i++) {
            dfs(grid, i, 0);
            dfs(grid, i, n - 1);
        }

        for (int j = 0; j < n; j++) {
            dfs(grid, 0, j);
            dfs(grid, m - 1, j);
        }

        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    count++;
                }
            }
        }

        return count;
    }

    private void dfs(int[][] grid, int i, int j) {
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || 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);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1020 (Number of Enclaves)?

This page provides optimized solutions for LeetCode problem 1020 (Number of Enclaves) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1020 (Number of Enclaves)?

The time complexity for LeetCode 1020 (Number of Enclaves) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1020 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1020 in Java, C++, or Python.

Back to LeetCode Solutions