Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second solution in Clear category for Calculate Islands by colinmcnicholl
def area_islands(map):
"""Input: A map as a list of lists with 1 (land) or 0 (water).
Output: A list of integers, 0 if cells water and positive integer if
connected cells.
"""
H, W = len(map), len(map[0])
seen = set()
def area(r, c):
if not (0 <= r < len(map) and 0 <= c < len(map[0])
and (r, c) not in seen and map[r][c]):
return 0
seen.add((r, c))
neighbors = [(r-1, c-1), (r-1, c), (r-1, c+1), (r, c-1),
(r, c+1), (r+1, c-1), (r+1, c), (r+1, c+1)]
return 1 + sum([area(*cell) for cell in neighbors])
return (area(r, c) for r in range(H) for c in range(W))
def checkio(land_map):
"""Input: A map as a list of lists with 1 (land) or 0 (water).
An island is a group of land cells surround by water. Cells are connected
by their edges and corners.
Function calculates the areas for each of the islands and return a list
of sizes (quantity of cells) in ascending order.
Output: The sizes of islands as a list of integers.
"""
areas = [cell for cell in area_islands(land_map) if cell]
areas.sort()
return areas
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([[0, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0]]) == [1, 3], "1st example"
assert checkio([[0, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 1, 0, 0]]) == [5], "2nd example"
assert checkio([[0, 0, 0, 0, 0, 0],
[1, 0, 0, 1, 1, 1],
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0]]) == [2, 3, 3, 4], "3rd example"
March 12, 2019
Comments: