# 1254. Number of Closed Islands
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
# Solution
Approach 1: dfs -- count number of islands, except for islands connected to the borders of the grid.
# Code (Python)
Approach 1:
class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
def dfs(r, c):
if grid[r][c] != 0:
return 1
grid[r][c] = -1
if r == 0 or c == 0 or r == len(grid) - 1 or c == len(grid[0]) - 1:
result = 0
else:
result = 1
for delta in ((0, 1), (0, -1), (1, 0), (-1, 0)):
if not(0 <= r + delta[0] < len(grid) and 0 <= c + delta[1] < len(grid[0])):
continue
if grid[r + delta[0]][c + delta[1]] != 0:
continue
if dfs(r + delta[0], c + delta[1]) == 0:
result = 0
return result
count = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == 0:
count += dfs(r, c)
return count
# Code (C++)
Approach 1:
Approach 2: