Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Hexagonal Islands by Oleg_Domokeev
from typing import Set, Iterable
grid = {a+b for a in 'ABCDEFGHIJKL' for b in '123456789'}
border = {a for a in grid if a[0] == 'A' or a[0] == 'L' or a[1] == '1' or a[1] == '9'}
def hexagonal_islands(coasts: Set[str]) -> Iterable[int]:
# determination if two cells are neighbours
def is_nb(a, b):
a0, a1, b0, b1 = ord(a[0]) - ord('A'), int(a[1]) - 1, ord(b[0]) - ord('A'), int(b[1]) - 1
if a0 == b0 and abs(a1 - b1) == 1:
return True
if abs(a0 - b0) == 1:
if a1 == b1 or (a0 % 2 == 0 and a1 - b1 == 1) or (a0 % 2 == 1 and a1 - b1 == -1):
return True
return False
#splitting the set of cells into islands
def inseln(cells):
result = []
while cells:
stack, isle = {cells.pop()}, set()
while stack:
isle |= stack
stack = {cell for cell in cells for elem in stack if is_nb(cell, elem)}
cells -= set(stack)
result.append(isle)
return result
#islands - the list of islands from coast cells
#free - the list of separated zone from the rest of the cells in grid
islands, free = inseln(coasts.copy()), inseln(grid - coasts)
#adding any inner zone to appropriate island
while free:
inner = free.pop()
#the zone that connect to the board of the grid can not be the inner part of any island
if inner.isdisjoint(border):
for isle in islands:
if any(is_nb(x, y) for x in inner for y in isle):
isle |= inner
break
return map(len, islands)
July 31, 2019
Comments: