Leetcode 1254: Number of Closed Islands

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

You are given a 2D grid with 0s (land) and 1s (water). An island is a group of 0s connected 4-directionally, and a closed island is a group of 0s completely surrounded by 1s. Your task is to count how many closed islands are present in the grid.
Problem
Approach
Steps
Complexity
Input: The input consists of a 2D grid with 0s and 1s.
Example: grid = [[1,1,1,1,1,1,1,0], [1,0,0,0,0,1,1,0], [1,0,1,0,1,1,1,0], [1,0,0,0,0,1,0,1], [1,1,1,1,1,1,1,0]]
Constraints:
• 1 <= grid.length, grid[0].length <= 100
• 0 <= grid[i][j] <= 1
Output: The output is a single integer representing the number of closed islands.
Example: Output: 2
Constraints:
• The number of closed islands can be at least 0.
Goal: The goal is to count the number of closed islands in the grid.
Steps:
• Loop through the grid, marking water cells connected to the boundary.
• Perform a depth-first search (DFS) to explore each closed island.
• Count each closed island and ensure no boundary cell is part of a closed island.
Goal: The grid dimensions are within 1 to 100 rows and columns.
Steps:
• 1 <= grid.length, grid[0].length <= 100
• 0 <= grid[i][j] <= 1
Assumptions:
• The grid is composed of only 0s and 1s.
• Boundary cells are considered to be part of the outer boundary.
Input: Input: [[1,1,1,1,1,1,1,0], [1,0,0,0,0,1,1,0], [1,0,1,0,1,1,1,0], [1,0,0,0,0,1,0,1], [1,1,1,1,1,1,1,0]]
Explanation: The grid contains two closed islands, both of which are surrounded by water.

Link to LeetCode Lab


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