From e1b3928cf41ba8c869232b1623aafbaf5bb6d2e5 Mon Sep 17 00:00:00 2001 From: Eclypsed Date: Tue, 14 Oct 2025 08:20:28 -0400 Subject: [PATCH] Basic Graphs: First working solution --- Basic-Graphs/cs412_islands_a.py | 47 ++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/Basic-Graphs/cs412_islands_a.py b/Basic-Graphs/cs412_islands_a.py index 8febec9..05d53df 100644 --- a/Basic-Graphs/cs412_islands_a.py +++ b/Basic-Graphs/cs412_islands_a.py @@ -9,6 +9,39 @@ Honor Code and Acknowledgments: """ +def explore_island(grid: list[list[int]], start: tuple[int, int]) -> int: + n: int = len(grid) + size: int = 0 + + def recurse(coord: tuple[int, int]): + x, y = coord + + if grid[y][x] == 0: + return + + nonlocal size + size += 1 + grid[y][x] = 0 + + neighbors: list[tuple[int, int]] = [] + + if y > 0: + neighbors.append((x, y - 1)) + if y < n - 1: + neighbors.append((x, y + 1)) + if x > 0: + neighbors.append((x - 1, y)) + if x < n - 1: + neighbors.append((x + 1, y)) + + for neighbor in neighbors: + recurse(neighbor) + + recurse(start) + + return size + + # All modules for CS 412 must include a main method that allows it # to imported and invoked from other python scripts def main(): @@ -16,7 +49,19 @@ def main(): matrix: list[list[int]] = [list(map(int, input().split())) for _ in range(0, n)] - pass + largest_island: int = -1 + + for y in range(0, n): + for x in range(0, n): + if matrix[y][x] == 0: + continue + + island_size: int = explore_island(matrix, (x, y)) + + if island_size > largest_island: + largest_island = island_size + + print(largest_island) if __name__ == "__main__":