counting islands with dfs
This commit is contained in:
parent
e89f564dd6
commit
f1f2302acd
@ -1,7 +1,51 @@
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
from const import *
|
||||||
|
from typing import List, Dict, Tuple
|
||||||
|
|
||||||
|
import numpy.typing as npt
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Position:
|
class Position:
|
||||||
row: int
|
row: int
|
||||||
col: int
|
col: int
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
def count_islands(grid: npt.NDArray, positions: List[Position], rows: int = ROWS, cols: int = COLUMNS) -> int:
|
||||||
|
visited = {}
|
||||||
|
|
||||||
|
for position in positions:
|
||||||
|
visited[(position.row, position.col)] = False
|
||||||
|
|
||||||
|
islands = 0
|
||||||
|
|
||||||
|
for position in positions:
|
||||||
|
if not visited[(position.row, position.col)]:
|
||||||
|
dfs(grid, visited, position, rows, cols)
|
||||||
|
islands += 1
|
||||||
|
|
||||||
|
return islands
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
from map_importer_exporter import export_map
|
from map_importer_exporter import export_map
|
||||||
from genome import Genome
|
from genome import Genome
|
||||||
|
from common import count_islands
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
@ -7,6 +8,7 @@ def main() -> None:
|
|||||||
print(example_genome.knights_red)
|
print(example_genome.knights_red)
|
||||||
print(example_genome.knights_blue)
|
print(example_genome.knights_blue)
|
||||||
print(example_genome.grid)
|
print(example_genome.grid)
|
||||||
|
print(count_islands(example_genome.grid, example_genome.sands + example_genome.waters))
|
||||||
# export_map(example_genome.grid) fixme: FileNotFoundError
|
# export_map(example_genome.grid) fixme: FileNotFoundError
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user