Skip to content

Instantly share code, notes, and snippets.

@PeterWaIIace
Created December 7, 2023 20:12
Show Gist options
  • Save PeterWaIIace/632ce21ae1b795911fc4ad4dfe5c48af to your computer and use it in GitHub Desktop.
Save PeterWaIIace/632ce21ae1b795911fc4ad4dfe5c48af to your computer and use it in GitHub Desktop.
[BFS] count islands
from collections import deque
def count_islands(matrix):
if not matrix:
return 0
visited = set()
islands = 0
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if(matrix[i][j] == 1) and (i,j) not in visited:
islands += 1
bfs(matrix,i,j,visited)
return islands
def bfs(matrix,i,j,visited):
directions = [(-1,0),(0,1),(1,0),(0,-1)] # left, up, right, down
queue = deque([(i,j)])
visited.add((i,j))
while queue:
curr_i, curr_j = queue.popleft()
for di,dj in directions:
ni, nj = curr_i + di, curr_j + dj
if ni < len(matrix) and ni >= 0 and nj < len(matrix[i]) and nj >= 0:
if (ni, nj) not in visited and matrix[ni][nj] == 1:
queue.append((ni, nj))
visited.add((ni, nj))
# Example matrix representing islands (1) and water (0)
# matrix_example = [
# [1, 1, 0, 0, 0],
# [1, 1, 0, 0, 1],
# [0, 0, 0, 1, 1],
# [0, 0, 0, 0, 0],
# [1, 0, 1, 0, 1]
# ]
matrix_example = [[]]
print("Number of Islands:", count_islands(matrix_example)) # Output: 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment