Files
CS412-Applied-Algorithms/Basic-Graphs/cs412_islands_a.py

76 lines
1.7 KiB
Python
Raw Normal View History

"""
name: Nicholas Tamassia
Honor Code and Acknowledgments:
This work complies with the JMU Honor Code.
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: LandGrid, start: tuple[int, int]) -> int:
num_rows, num_cols = grid.shape
2025-10-14 08:20:28 -04:00
size: int = 0
def recurse(coord: tuple[int, int]):
x, y = coord
if not grid[y, x]:
2025-10-14 08:20:28 -04:00
return
nonlocal size
size += 1
grid[y, x] = False
2025-10-14 08:20:28 -04:00
neighbors: list[tuple[int, int]] = []
if y > 0:
neighbors.append((x, y - 1))
if y < num_rows - 1:
2025-10-14 08:20:28 -04:00
neighbors.append((x, y + 1))
if x > 0:
neighbors.append((x - 1, y))
if x < num_cols - 1:
2025-10-14 08:20:28 -04:00
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():
n: int = int(input())
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
2025-10-14 08:20:28 -04:00
largest_island: int = -1
for y in range(0, num_rows):
for x in range(0, num_cols):
if not land_grid[y, x]:
2025-10-14 08:20:28 -04:00
continue
island_size: int = explore_island(land_grid, (x, y))
2025-10-14 08:20:28 -04:00
if island_size > largest_island:
largest_island = island_size
print(largest_island)
if __name__ == "__main__":
main()