|
| 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