Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second solution in Clear category for Calculate Islands by Sim0000
from collections import deque
def checkio(data):
area = []
for x, y in [(x, y) for y in range(len(data)) for x in range(len(data[0]))]:
if data[y][x] != 1: continue
q = deque([(x, y)])
count = 0
while len(q) != 0:
x, y = q.popleft()
if data[y][x] != 1: continue
data[y][x] = 0
count += 1
for dx, dy in [(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]:
x1, y1 = x + dx, y + dy
if 0 <= x1 < len(data[0]) and 0 <= y1 < len(data): q.append((x1, y1))
area.append(count)
return sorted(area)
#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 1, 2014
Comments: