Skip to content

Commit 4a2d457

Browse files
xmichael446cclauss
andauthored
* Add files via upload * Update and rename count_islands.py to count_islands_in_matrix.py * Update matrix/count_islands_in_matrix.py Co-authored-by: Christian Clauss <[email protected]> * Update matrix/count_islands_in_matrix.py Co-authored-by: Christian Clauss <[email protected]> * Update matrix/count_islands_in_matrix.py Co-authored-by: Christian Clauss <[email protected]> * Reformat count islands.py * Indent Python code with 4 spaces, not tabs * Update count_islands_in_matrix.py * Add type hints for return values Co-authored-by: Christian Clauss <[email protected]>
1 parent b9e5259 commit 4a2d457

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

matrix/count_islands_in_matrix.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# An island in matrix is a group of linked areas, all having the same value.
2+
# This code counts number of islands in a given matrix, with including diagonal
3+
# connections.
4+
5+
6+
class matrix: # Public class to implement a graph
7+
def __init__(self, row: int, col: int, graph: list):
8+
self.ROW = row
9+
self.COL = col
10+
self.graph = graph
11+
12+
def is_safe(self, i, j, visited) -> bool:
13+
return (
14+
0 <= i < self.ROW
15+
and 0 <= j < self.COL
16+
and not visited[i][j]
17+
and self.graph[i][j]
18+
)
19+
20+
def diffs(self, i, j, visited): # Checking all 8 elements surrounding nth element
21+
rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order
22+
colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]
23+
visited[i][j] = True # Make those cells visited
24+
for k in range(8):
25+
if self.is_safe(i + rowNbr[k], j + colNbr[k], visited):
26+
self.diffs(i + rowNbr[k], j + colNbr[k], visited)
27+
28+
def count_islands(self) -> int: # And finally, count all islands.
29+
visited = [[False for j in range(self.COL)] for i in range(self.ROW)]
30+
count = 0
31+
for i in range(self.ROW):
32+
for j in range(self.COL):
33+
if visited[i][j] is False and self.graph[i][j] == 1:
34+
self.diffs(i, j, visited)
35+
count += 1
36+
return count

0 commit comments

Comments
 (0)