forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount_islands_in_matrix.py
37 lines (32 loc) · 1.45 KB
/
count_islands_in_matrix.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 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.
classMatrix: # Public class to implement a graph
def__init__(self, row: int, col: int, graph: list[list[bool]]) ->None:
self.ROW=row
self.COL=col
self.graph=graph
defis_safe(self, i: int, j: int, visited: list[list[bool]]) ->bool:
return (
0<=i<self.ROW
and0<=j<self.COL
andnotvisited[i][j]
andself.graph[i][j]
)
defdiffs(self, i: int, j: int, visited: list[list[bool]]) ->None:
# Checking all 8 elements surrounding nth element
row_nbr= [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order
col_nbr= [-1, 0, 1, -1, 1, -1, 0, 1]
visited[i][j] =True# Make those cells visited
forkinrange(8):
ifself.is_safe(i+row_nbr[k], j+col_nbr[k], visited):
self.diffs(i+row_nbr[k], j+col_nbr[k], visited)
defcount_islands(self) ->int: # And finally, count all islands.
visited= [[Falseforjinrange(self.COL)] foriinrange(self.ROW)]
count=0
foriinrange(self.ROW):
forjinrange(self.COL):
ifvisited[i][j] isFalseandself.graph[i][j] ==1:
self.diffs(i, j, visited)
count+=1
returncount