2020-06-16 12:36:09 +00:00
|
|
|
# An island in matrix is a group of linked areas, all having the same value.
|
|
|
|
# This code counts number of islands in a given matrix, with including diagonal
|
|
|
|
# connections.
|
|
|
|
|
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
class Matrix: # Public class to implement a graph
|
2022-10-04 18:05:56 +00:00
|
|
|
def __init__(self, row: int, col: int, graph: list[list[bool]]) -> None:
|
2020-06-16 12:36:09 +00:00
|
|
|
self.ROW = row
|
|
|
|
self.COL = col
|
|
|
|
self.graph = graph
|
|
|
|
|
2022-10-04 18:05:56 +00:00
|
|
|
def is_safe(self, i: int, j: int, visited: list[list[bool]]) -> bool:
|
2020-06-16 12:36:09 +00:00
|
|
|
return (
|
|
|
|
0 <= i < self.ROW
|
|
|
|
and 0 <= j < self.COL
|
|
|
|
and not visited[i][j]
|
|
|
|
and self.graph[i][j]
|
|
|
|
)
|
|
|
|
|
2022-10-04 18:05:56 +00:00
|
|
|
def diffs(self, i: int, j: int, visited: list[list[bool]]) -> None:
|
|
|
|
# Checking all 8 elements surrounding nth element
|
2022-10-12 22:54:20 +00:00
|
|
|
row_nbr = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order
|
|
|
|
col_nbr = [-1, 0, 1, -1, 1, -1, 0, 1]
|
2020-06-16 12:36:09 +00:00
|
|
|
visited[i][j] = True # Make those cells visited
|
|
|
|
for k in range(8):
|
2022-10-12 22:54:20 +00:00
|
|
|
if self.is_safe(i + row_nbr[k], j + col_nbr[k], visited):
|
|
|
|
self.diffs(i + row_nbr[k], j + col_nbr[k], visited)
|
2020-06-16 12:36:09 +00:00
|
|
|
|
|
|
|
def count_islands(self) -> int: # And finally, count all islands.
|
|
|
|
visited = [[False for j in range(self.COL)] for i in range(self.ROW)]
|
|
|
|
count = 0
|
|
|
|
for i in range(self.ROW):
|
|
|
|
for j in range(self.COL):
|
|
|
|
if visited[i][j] is False and self.graph[i][j] == 1:
|
|
|
|
self.diffs(i, j, visited)
|
|
|
|
count += 1
|
|
|
|
return count
|