Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Creative category for Calculate Islands by freeman_lex
def checkio(M):
A = [(i, j) for i in range(len(M)) for j in range(len(M[0])) if M[i][j]]
B = [set([i, j]) for i in A for j in A if abs(j[0]-i[0])<=1 and abs(j[1]-i[1])<=1]
C=[]
for j in B:
for i in B:
if j & i: j |= i
if j not in C: C.append(j)
D = sorted([len(i) for i in C])
return [D[-1]] if sum(D) > len(A) else D
#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"
July 1, 2014