Ditched numpy, it's slow. Changed recursive call structure

This commit is contained in:
2025-10-14 18:12:39 -04:00
parent 82ba7de3eb
commit a730e01e9c

View File

@@ -8,38 +8,30 @@ Honor Code and Acknowledgments:
Comments here on your code and submission. Comments here on your code and submission.
""" """
import numpy as np
type LandGrid = np.ndarray[tuple[int, int], np.dtype[np.bool]] def explore_island(grid: list[list[int]], start: tuple[int, int]) -> int:
num_rows: int = len(grid)
num_cols: int = len(grid[0])
def explore_island(grid: LandGrid, start: tuple[int, int]) -> int:
num_rows, num_cols = grid.shape
size: int = 0 size: int = 0
def recurse(coord: tuple[int, int]): def recurse(coord: tuple[int, int]):
x, y = coord x, y = coord
if not grid[y, x]: if grid[y][x] == 0:
return return
nonlocal size nonlocal size
size += 1 size += 1
grid[y, x] = False grid[y][x] = 0
neighbors: list[tuple[int, int]] = []
if y > 0: if y > 0:
neighbors.append((x, y - 1)) recurse((x, y - 1))
if y < num_rows - 1: if y < num_rows - 1:
neighbors.append((x, y + 1)) recurse((x, y + 1))
if x > 0: if x > 0:
neighbors.append((x - 1, y)) recurse((x - 1, y))
if x < num_cols - 1: if x < num_cols - 1:
neighbors.append((x + 1, y)) recurse((x + 1, y))
for neighbor in neighbors:
recurse(neighbor)
recurse(start) recurse(start)
@@ -51,16 +43,16 @@ def explore_island(grid: LandGrid, start: tuple[int, int]) -> int:
def main(): def main():
n: int = int(input()) n: int = int(input())
raw_matrix: list[list[int]] = [list(map(int, input().split())) for _ in range(0, n)] land_grid: list[list[int]] = [list(map(int, input().split())) for _ in range(0, n)]
land_grid: LandGrid = np.array(raw_matrix, dtype=bool) num_rows: int = n
num_rows, num_cols = land_grid.shape num_cols: int = len(land_grid[0])
largest_island: int = -1 largest_island: int = -1
for y in range(0, num_rows): for y in range(0, num_rows):
for x in range(0, num_cols): for x in range(0, num_cols):
if not land_grid[y, x]: if land_grid[y][x] == 0:
continue continue
island_size: int = explore_island(land_grid, (x, y)) island_size: int = explore_island(land_grid, (x, y))