philosyang.com

1254. Number of Closed Islands | 1659

Knowingly not using union find on this one. Also really, really busy at work during Wednesdays.

 1class Solution:
 2    def closedIsland(self, grid: List[List[int]]) -> int:
 3        # try not to use union find, duh
 4        # idea:
 5        # traverse grid normally, mark and track visited locations
 6        # when greeted a 0, we start a bfs search and keep track of all the connected 0s
 7        # island_number += 1
 8        # continue to traverse grid, skip any previously visited location
 9        # until the bottom right most square
10
11        island_number = 0
12        visited = set()  # (0,0), (0,1), ...
13        m, n = len(grid), len(grid[0])  # height, left-to-right
14
15        for i in range(m):
16            for j in range(n):
17                square = (i, j)
18                if square in visited or grid[i][j] == 1:
19                    continue
20
21                q = deque([square])
22                is_closed_island = True
23
24                while q:
25                    tile = q.popleft()
26                    visited.add(tile)
27                    x, y = tile
28                    # if edge land
29                    if is_closed_island and (x in [0, m - 1] or y in [0, n - 1]):
30                        is_closed_island = False
31                    # right
32                    if y + 1 < n and (x, y + 1) not in visited and grid[x][y + 1] == 0:
33                        q.append((x, y + 1))
34                    # left
35                    if y - 1 > -1 and (x, y - 1) not in visited and grid[x][y - 1] == 0:
36                        q.append((x, y - 1))
37                    # down
38                    if x + 1 < m and (x + 1, y) not in visited and grid[x + 1][y] == 0:
39                        q.append((x + 1, y))
40                    # up
41                    if x - 1 > -1 and (x - 1, y) not in visited and grid[x - 1][y] == 0:
42                        q.append((x - 1, y))
43
44                if is_closed_island:
45                    island_number += 1
46
47        return island_number

It’s O(M*N) no matter which method you use.

#Array #Breadth-First-Search #Python