From 82ba7de3ebacca7e7f6dab465718018c6ffb11ee Mon Sep 17 00:00:00 2001 From: Eclypsed Date: Tue, 14 Oct 2025 09:41:47 -0400 Subject: [PATCH] Basic-Graphs: Input grids can now be rectagular, moved to numpy --- Basic-Graphs/cs412_islands_a.py | 29 ++++++++++++++++++----------- Basic-Graphs/inputs/sample3.txt | 9 +++++++++ 2 files changed, 27 insertions(+), 11 deletions(-) create mode 100644 Basic-Graphs/inputs/sample3.txt diff --git a/Basic-Graphs/cs412_islands_a.py b/Basic-Graphs/cs412_islands_a.py index 05d53df..50a5050 100644 --- a/Basic-Graphs/cs412_islands_a.py +++ b/Basic-Graphs/cs412_islands_a.py @@ -8,30 +8,34 @@ Honor Code and Acknowledgments: Comments here on your code and submission. """ +import numpy as np -def explore_island(grid: list[list[int]], start: tuple[int, int]) -> int: - n: int = len(grid) +type LandGrid = np.ndarray[tuple[int, int], np.dtype[np.bool]] + + +def explore_island(grid: LandGrid, start: tuple[int, int]) -> int: + num_rows, num_cols = grid.shape size: int = 0 def recurse(coord: tuple[int, int]): x, y = coord - if grid[y][x] == 0: + if not grid[y, x]: return nonlocal size size += 1 - grid[y][x] = 0 + grid[y, x] = False neighbors: list[tuple[int, int]] = [] if y > 0: neighbors.append((x, y - 1)) - if y < n - 1: + if y < num_rows - 1: neighbors.append((x, y + 1)) if x > 0: neighbors.append((x - 1, y)) - if x < n - 1: + if x < num_cols - 1: neighbors.append((x + 1, y)) for neighbor in neighbors: @@ -47,16 +51,19 @@ def explore_island(grid: list[list[int]], start: tuple[int, int]) -> int: def main(): n: int = int(input()) - matrix: list[list[int]] = [list(map(int, input().split())) for _ in range(0, n)] + raw_matrix: list[list[int]] = [list(map(int, input().split())) for _ in range(0, n)] + + land_grid: LandGrid = np.array(raw_matrix, dtype=bool) + num_rows, num_cols = land_grid.shape largest_island: int = -1 - for y in range(0, n): - for x in range(0, n): - if matrix[y][x] == 0: + for y in range(0, num_rows): + for x in range(0, num_cols): + if not land_grid[y, x]: continue - island_size: int = explore_island(matrix, (x, y)) + island_size: int = explore_island(land_grid, (x, y)) if island_size > largest_island: largest_island = island_size diff --git a/Basic-Graphs/inputs/sample3.txt b/Basic-Graphs/inputs/sample3.txt new file mode 100644 index 0000000..dd59c36 --- /dev/null +++ b/Basic-Graphs/inputs/sample3.txt @@ -0,0 +1,9 @@ +8 +0 0 1 0 0 0 0 1 0 0 0 0 0 +0 0 0 0 0 0 0 1 1 1 0 0 0 +0 1 1 0 1 0 0 0 0 0 0 0 0 +0 1 0 0 1 1 0 0 1 0 1 0 0 +0 1 0 0 1 1 0 0 1 1 1 0 0 +0 0 0 0 0 0 0 0 0 0 1 0 0 +0 0 0 0 0 0 0 1 1 1 0 0 0 +0 0 0 0 0 0 0 1 1 0 0 0 0