Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import deque
- def count_islands(matrix):
- """
- Args:
- matrix(list_list_int32)
- Returns:
- int32
- """
- # Write your code here.
- row = len(matrix)
- col = len(matrix[0])
- visited = set()
- island = 0
- # extension => traverse the matrix: 1) land 2) in bounds 3) up down left right top-left top-right bottom-left bottom-right
- def get_neighbors(i, j):
- neighbors = []
- # up
- if i-1 >= 0 and matrix[i-1][j] == 1:
- neighbors.append((i-1, j)) #query
- # down
- if i+1 < row and matrix[i+1][j] == 1:
- neighbors.append((i+1, j)) #query
- # left
- if j-1 >= 0 and matrix[i][j - 1] == 1:
- neighbors.append((i, j-1)) #query
- # right
- if j+1 < col and matrix[i][j + 1] == 1:
- neighbors.append((i, j+1)) #query
- #top-left
- if i-1 >= 0 and j-1 >= 0 and matrix[i-1][j-1] == 1:
- neighbors.append((i-1, j-1)) #query
- #top-right
- if i-1 >= 0 and j+1 < col and matrix[i-1][j+1] == 1:
- neighbors.append((i-1, j+1)) #query
- #bottom-left
- if i+1 < row and j-1 >= 0 and matrix[i+1][j-1] == 1:
- neighbors.append((i+1, j-1)) #query
- #bottom-right
- if i+1 < row and j+1 < col and matrix[i+1][j+1] == 1:
- neighbors.append((i+1, j+1)) #query
- return neighbors
- # bfs
- def bfs(i, j):
- visited.add((i, j))
- q = deque()
- q.append((i, j))
- while q:
- c_i, c_j = q.popleft()
- for n_i, n_j in get_neighbors(c_i, c_j):
- if (n_i, n_j) not in visited: # query!
- visited.add((n_i, n_j))
- q.append((n_i, n_j))
- return
- # outer loop
- for i in range(row):
- for j in range(col):
- if (i,j) not in visited and matrix[i][j] == 1:
- bfs(i, j)
- island += 1
- return island
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement