# Given a 2D array binaryMatrix of 0s and 1s, implement a function getNumberOfIslands that returns the number of islands of 1s in binaryMatrix.
The problem is asking us to identify the number of islands or cluster of 1s in a binary matrix. If we simply count the number of 1s it’ll be difficult to track which 1 belong to which cluster and thus will not give accurate answer. The depth first traversal approach is one that’s easy to understand, we’ll loop over the entire matrix and if the number is an 1, we will utlize dpeth first traversal to find all 1s linked or inter-linked to the 1 that initiated the dfs.
First, we must create a function to loop over the matrix
def count_island(bm): # bm: binary matrix
l = len(bm) # bm width
h = len(bm) # bm height
if not h:
return 0 # if no bm
for r in range(h):
for c in range(l):
if bm[r][c]: # if true, or val is 1
count += 1 # new cluster
dfs(bm, r, c) # erase all 1s in this cluster
Following we can write a depth first traversal function to traverse all 1s in a cluster.
def dfs(bm, r, c):