Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Calculate Islands by Bilou06
import itertools
def checkio(data):
ret = []
counted = [[False for a in l] for l in data]
for i in range(len(data)):
for j in range(len(data[0])):
if counted[i][j] or data[i][j] == 0:
continue
count = 0
next = [(i,j)]
while len(next):
x,y = next.pop()
if x<0 or y<0 or x>=len(data) or y>=len(data[0]) or counted[x][y] or data[x][y] == 0:
continue
counted[x][y] = True
count += 1
for (a,b) in itertools.product([-1,0,1], [-1,0,1]):
next.append((x+a, y+b))
ret.append(count)
ret.sort()
return ret
#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"
June 19, 2013