Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
depth-first search solution in Clear category for The Territory of Go by David_Jones
from itertools import product
def territory(board):
def neighbors(cell):
(x,y) = cell
for (x,y) in ((x-1,y), (x+1,y), (x,y-1), (x,y+1)):
if 0 <= x < n and 0 <= y < n:
yield (x,y)
n = len(board)
counted = set()
score = {'B': 0, 'W': 0}
for (x,y) in product(range(n), repeat=2):
if board[x][y] == '+' and (x,y) not in counted:
points = 0
stone_colors = set()
counted.add((x,y))
stack = [(x,y)]
while stack:
points += 1
for (x,y) in neighbors(stack.pop()):
if (x,y) in counted:
continue
if board[x][y] == '+':
stack.append((x,y))
counted.add((x,y))
else:
stone_colors.add(board[x][y])
if len(stone_colors) == 1:
score[stone_colors.pop()] += points
return score
July 1, 2019