Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
18-liner: jump from island to island. solution in Clear category for Calculate Islands by Stensen
from itertools import starmap
DIRS = {(1, 1), (0, 1), (1, 0), (-1, 0), (0, -1), (-1, 1), (1, -1), (-1, -1)}
neighbrs = lambda x, y, arr: [(x+i, y+j) for i, j in DIRS \
if 0 <= x+i < len(arr) and 0 <= y+j < len(arr[0])]
def checkio(arr):
visited, answer = {0}, []
for a, b in [(i, j) for i in range(len(arr)) for j in range(len(arr[0])) if arr[i][j] == 1]:
neighbors = neighbrs(a, b, arr)
if (a, b) in visited: continue
count = 0
while neighbors:
x, y = neighbors.pop()
if arr[x][y] == 1 and (x, y) not in visited:
neighbors.extend([i for i in neighbrs(x, y, arr) if i not in neighbors])
visited.add((x, y))
count += 1
answer.append(count if count else 1)
return sorted(answer)
Nov. 23, 2020