I am trying to count the number of islands (a group of connected 1s forms an island) in a 2D binary matrix.
Example:
[
[1, 1, 0, 0, 0],
[0, 1, 0, 0,
Your algorithm is almost correct except for the line 21:
if r != i and c != j:
cnt += count_houses(mat, visited, r, c)
Instead you want to use or
as you want to continue counting provided at least one of the coordinate is not the same as your center.
if r != i or c != j:
cnt += count_houses(mat, visited, r, c)
An alternate and more intuitive way to write this would be the following
if (r, c) != (i, j):
cnt += count_houses(mat, visited, r, c)
big hammer approach, for reference
had to add structure
argument np.ones((3,3))
to add diagonal connectivity
import numpy as np
from scipy import ndimage
ary = np.array([
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[1, 0, 1, 0, 1]
])
labeled_array, num_features = ndimage.label(ary, np.ones((3,3)))
labeled_array, num_features
Out[183]:
(array([[1, 1, 0, 0, 0],
[0, 1, 0, 0, 2],
[1, 0, 0, 2, 2],
[0, 0, 0, 0, 0],
[3, 0, 4, 0, 5]]), 5)