Leetcode 1020: Number of Enclaves

grid47
grid47
Exploring patterns and algorithms
Jul 28, 2024 7 min read

You are given a grid of size m x n where each cell is either land (1) or sea (0). Your task is to determine the number of land cells that are completely enclosed by sea cells. A land cell is considered enclosed if it cannot reach the boundary of the grid via other land cells.
Problem
Approach
Steps
Complexity
Input: The input consists of an m x n grid, where grid[i][j] is either 1 (land) or 0 (sea).
Example: grid = [[0, 0, 0, 0], [1, 0, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]]
Constraints:
• 1 <= m, n <= 500
• grid[i][j] is either 0 or 1
Output: Return the number of land cells that are completely enclosed by sea cells, i.e., they cannot reach the boundary of the grid.
Example: Output: 3
Constraints:
• The returned number should be an integer representing the count of enclosed land cells.
Goal: To determine which land cells are enclosed, we need to find and mark all the land cells connected to the boundary of the grid, and then count the remaining land cells.
Steps:
• 1. Traverse the boundary of the grid and mark all land cells connected to it using depth-first search (DFS).
• 2. After marking the reachable land cells, the remaining unmarked land cells are enclosed.
• 3. Count and return the number of enclosed land cells.
Goal: Make sure the algorithm works efficiently within the grid size constraints and correctly identifies enclosed land cells.
Steps:
• The grid can be as large as 500 x 500, so the solution should handle grids of this size.
Assumptions:
• The input grid is valid and contains only 0s and 1s.
Input: Input: grid = [[0, 0, 0, 0], [1, 0, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]]
Explanation: In this case, the 1s in positions (1, 0), (1, 2), and (2, 1) are enclosed by 0s. The land cell at position (2, 2) is not enclosed because it is connected to the boundary. Thus, the output is 3.

Input: Input: grid = [[0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 0, 0]]
Explanation: In this case, all the 1s are either connected to the boundary or can reach the boundary through other land cells. Therefore, no land cells are enclosed, and the output is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus