Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Calculate Islands by mfrankowski
import itertools
def checkio1(x,y,w,l):
a=[x+i for i in range(-1,2) if x+i in range(0,w)]
b=[y+i for i in range(-1,2) if y+i in range(0,l)]
return list(itertools.product(a,b))
def checkio(land_map):
w=len(land_map)
l=len(land_map[0])
u=[(x,y) for x in range(w) for y in range(l)]
c=[]
while u:
x,y=u.pop(0)
if land_map[x][y]:
n=1
k=checkio1(x,y,w,l)
while k:
i=k.pop(0)
if i in u:
u.remove(i)
if land_map[i[0]][i[1]]:
n=n+1
k.extend(checkio1(i[0],i[1],w,l))
c.append(n)
c.sort()
return c
#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"
Nov. 11, 2016