Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
use Set Objects solution in Clear category for The Territory of Go by kurosawa4434
def territory(board):
width, height = len(board[0]), len(board)
def check_adjacent(point):
y, x = point
empty_points = set()
find_stones = set()
for ty, tx in ((y-1, x), (y+1, x), (y, x-1), (y, x+1)):
if ty not in (-1, height) and tx not in (-1, width):
if board[ty][tx] == '+':
empty_points.add((ty, tx))
else:
find_stones.add(board[ty][tx])
return empty_points, find_stones
def search(y, x, done_points):
next_points = {(y, x)}
stone_kinds = set()
sub_total = 1
while next_points:
search_points = next_points
next_points = set()
for p in search_points:
points, stones = check_adjacent(p)
stone_kinds |= stones
next_points |= points
next_points -= done_points
done_points |= next_points
sub_total += len(next_points)
return stone_kinds, sub_total
result = {'B': 0, 'W': 0}
done_points = set()
for y, row in enumerate(board):
for x, stone in enumerate(row):
if stone == '+' and (y, x) not in done_points:
done_points.add((y, x))
edges, area = search(y, x, done_points)
if len(edges) == 1:
result[edges.pop()] += area
return result
if __name__ == '__main__':
assert territory(['++B++++++',
'+BB++++++',
'BB+++++++',
'+++++++++',
'+++++++++',
'++WWW++++',
'++W+W++++',
'++WWW++++',
'+++++++++']) == {'B': 3, 'W': 1}
print("Coding complete? Click 'Check' to earn cool rewards!")
May 31, 2018
Comments: