Solving Leetcode Interviews in Seconds with AI: Number of Closed Islands
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1254" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s. Return the number of closed islands. Example 1: Input: 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]] Output: 2 Explanation: Islands in gray are closed because they are completely surrounded by water (group of 1s). Example 2: Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]] Output: 1 Example 3: Input: grid = [[1,1,1,1,1,1,1], [1,0,0,0,0,0,1], [1,0,1,1,1,0,1], [1,0,1,0,1,0,1], [1,0,1,1,1,0,1], [1,0,0,0,0,0,1], [1,1,1,1,1,1,1]] Output: 2 Constraints: 1 <= grid.length, grid[0].length <= 100 0 <= grid[i][j] <=1
Explanation
- Identify and Eliminate Non-Closed Islands: Perform a Depth-First Search (DFS) or Breadth-First Search (BFS) starting from land cells (0s) located on the boundary of the grid. Mark these islands as "non-closed" by changing their value to a different value (e.g., 2). This step ensures that any island connected to the boundary cannot be a closed island.
Count Closed Islands: Iterate through the grid again. For each remaining land cell (0), perform a DFS or BFS to mark the entire island as visited (e.g., change its value to 2) and increment the closed island count. Since the non-closed islands were eliminated, any remaining island must be a closed island.
Complexity: O(m n) runtime, where m is the number of rows and n is the number of columns in the grid. O(m n) storage in the worst-case scenario, due to the call stack of the recursive DFS approach.
Code
def closedIsland(grid):
rows, cols = len(grid), len(grid[0])
def dfs(row, col):
if row < 0 or row >= rows or col < 0 or col >= cols or grid[row][col] != 0:
return
grid[row][col] = 2 # Mark as visited (part of a non-closed island or visited closed island)
dfs(row + 1, col)
dfs(row - 1, col)
dfs(row, col + 1)
dfs(row, col - 1)
# Eliminate islands connected to the boundary
for i in range(rows):
for j in range(cols):
if (i == 0 or i == rows - 1 or j == 0 or j == cols - 1) and grid[i][j] == 0:
dfs(i, j)
# Count the remaining closed islands
closed_islands = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == 0:
closed_islands += 1
dfs(i, j) # Mark the closed island as visited
return closed_islands