Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Calculate Islands by Andreas_Strus
class island:
"""stores ilands"""
def __init__(self, name, points = [], position =[]):
self.name = name
self.position = position
self.X = position[0]
self.Y = position[1]
self.points = [position]
self.area = len(self.points)
def check(self, used = [], mapa = []):
points_child = []
for x in [1, 0, -1]:
if (self.X + x) in range(len(mapa)):
for y in [1, 0, -1]:
if (self.Y + y) in range(len(mapa[x])):
if [self.X + x, self.Y + y] not in used and mapa[self.X + x][self.Y + y] == 1:
points_child = points_child + [[self.X + x, self.Y + y]]
self.points = self.points + points_child
points_new = points_child
used = used + points_new
while points_child != []:
points_new = points_child
points_child = []
for n in range(len(points_new)):
for x in [1, 0, -1]:
if (int(points_new[n][0]) + x) in range(len(mapa)):
for y in [1, 0, -1]:
if (int(points_new[n][1]) + y) in range(len(mapa[x])):
if [int(points_new[n][0]) + x, int(points_new[n][1]) + y] not in used and mapa[int(points_new[n][0]) + x][int(points_new[n][1]) + y] == 1:
points_child = points_child + [[points_new[n][0] + x, points_new[n][1] + y]]
used = used + [[points_new[n][0] + x, points_new[n][1] + y]]
self.points = self.points + [[points_new[n][0] + x, points_new[n][1] + y]]
self.area = len(self.points)
def checkio(land_map):
x = 0
y = 0
islands = []
used = []
n = 0
for x in range(len(land_map)):
for y in range(len(land_map[x])):
if land_map[x][y] == 1 and [x, y] not in used:
used = used + [[x, y]]
new_island = island(n, [[x, y]], [x, y])
new_island.check(used, land_map)
used = used + new_island.points
print(used)
islands = islands + [new_island]
n = n + 1
arreas = []
for m in range(n):
area = islands[m].area
arreas = arreas + [area]
arreas.sort()
print(arreas)
return arreas
#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"
Oct. 26, 2016