Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Calculate Islands by Rounin
def validIndices(data, row, col):
return row >= 0 and col >= 0 and row < len(data) and col < len(data[0])
def searchNeighbours(data, classes, row, col, nodeclass):
if data[row][col] == 0:
classes[str([row,col])] = 'Empty square'
elif not str([row,col]) in classes:
classes[str([row,col])] = str([row,col])
for r in range(row-1, row+2):
for c in range(col-1, col+2):
if not validIndices(data, r, c) or ((r==row)and(c==col)):
continue
if(data[r][c] == data[row][col]):
if str([r,c]) in classes:
classes[str([row,col])] = classes[str([r,c])]
else:
classes[str([r,c])] = classes[str([row,col])]
searchNeighbours(data, classes, r,c, nodeclass)
def checkio(data):
classes = {}
for row in range(len(data)):
for col in range(len(data[0])):
searchNeighbours(data, classes, row, col, [row, col])
sizes = {}
for class1 in classes:
if classes[class1] == 'Empty square':
continue
class2 = classes[class1]
sizes[class2] = (sizes[class2] if class2 in sizes else 0) + 1
return sorted(sizes.values())
#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 21, 2017