2022-05-30 23:34:28 +02:00
|
|
|
from dataclasses import dataclass
|
2022-05-31 21:34:31 +02:00
|
|
|
from const import *
|
|
|
|
from typing import List, Dict, Tuple
|
|
|
|
|
|
|
|
import numpy.typing as npt
|
2022-05-30 23:34:28 +02:00
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class Position:
|
|
|
|
row: int
|
|
|
|
col: int
|
2022-05-31 21:34:31 +02:00
|
|
|
|
|
|
|
|
|
|
|
def dfs(grid: npt.NDArray, visited: Dict[Tuple[int, int], bool], position: Position, rows: int, cols: int) -> None:
|
|
|
|
visited[(position.row, position.col)] = True
|
|
|
|
|
|
|
|
row_vector = [0, 0, 1, -1]
|
|
|
|
col_vector = [-1, 1, 0, 0]
|
|
|
|
|
|
|
|
neighbours = []
|
|
|
|
for i in range(4):
|
|
|
|
rr = position.row + row_vector[i]
|
|
|
|
cc = position.col + col_vector[i]
|
|
|
|
if rr < 0 or rr >= ROWS:
|
|
|
|
continue
|
|
|
|
elif cc < 0 or cc >= COLUMNS:
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
p = Position(rr, cc)
|
|
|
|
if (p.row, p.col) in visited:
|
|
|
|
neighbours.append(p)
|
|
|
|
|
|
|
|
for neighbour in neighbours:
|
|
|
|
if not visited[(neighbour.row, neighbour.col)]:
|
|
|
|
dfs(grid, visited, neighbour, rows, cols)
|
|
|
|
|
|
|
|
|
2022-05-31 22:13:16 +02:00
|
|
|
def get_islands(grid: npt.NDArray, positions: List[Position], rows: int = ROWS, cols: int = COLUMNS) -> List[Position]:
|
|
|
|
"""it returns list of all islands roots"""
|
2022-05-31 21:34:31 +02:00
|
|
|
visited = {}
|
|
|
|
|
|
|
|
for position in positions:
|
|
|
|
visited[(position.row, position.col)] = False
|
|
|
|
|
|
|
|
islands = 0
|
2022-05-31 22:13:16 +02:00
|
|
|
roots = []
|
2022-05-31 21:34:31 +02:00
|
|
|
for position in positions:
|
|
|
|
if not visited[(position.row, position.col)]:
|
|
|
|
dfs(grid, visited, position, rows, cols)
|
2022-05-31 22:13:16 +02:00
|
|
|
roots.append(position)
|
2022-05-31 21:34:31 +02:00
|
|
|
islands += 1
|
|
|
|
|
2022-05-31 22:13:16 +02:00
|
|
|
return roots
|