Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
pop list and recursion for search solution in Clear category for Calculate Islands by pseudorandomcoder
from typing import List
# define land for clarity
LAND = 1
NEIGHBORS = [[i, j] for i in range(-1, 2) for j in range(-1, 2) if not (i == 0 and j == 0)]
def check_neighbors(land_map: List[List[int]], loc_list: List[List[int]],
loc2check: List[int]) -> int:
"""
recursive function to check neighbors near land that has been found
land_map: original, entire map
loc_list: list of map locations that haven't been checked
loc2check: check neighbors of this location
"""
additional_mass = 0
for n in NEIGHBORS:
test_loc = [loc2check[0]+n[0], loc2check[1]+n[1]]
if test_loc in loc_list:
loc_list.pop(loc_list.index(test_loc))
#check for land
if land_map[test_loc[0]][test_loc[1]] == LAND:
additional_mass += 1 + check_neighbors(land_map, loc_list, test_loc)
return additional_mass
def checkio(land_map: List[List[int]]) -> List[int]:
island_list = list()
i_len = len(land_map)
j_len = len(land_map[0])
# list of locations to check
loc_list = [[i, j] for i in range(i_len) for j in range(j_len)]
# check locations
while len(loc_list) > 0:
island_mass = 0
loc2check = loc_list.pop(0)
#check for new islands
if land_map[loc2check[0]][loc2check[1]] == LAND:
island_mass += 1 + check_neighbors(land_map, loc_list, loc2check)
island_list.append(island_mass)
return sorted(island_list)
July 4, 2018