Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Recursive solution in Clear category for The Territory of Go by Sim0000
def territory(board):
def check(y, x) -> bool:
if y < 0 or N <= y or x < 0 or N <= x or (y, x) in seen: return 0
if board[y][x] == '+':
seen.add((y, x))
return check(y - 1, x) + check(y + 1, x) + check(y, x - 1) + check(y, x + 1) + 1
color.add(board[y][x])
return 0
N = len(board)
score = {'B': 0, 'W' : 0}
seen = set()
for y in range(N):
for x in range(N):
if board[y][x] == '+' and (y, x) not in seen:
color = set()
count = check(y, x)
if len(color) == 1: score[color.pop()] += count
return score
if __name__ == '__main__':
print("Example:")
print(territory(['++B++++++',
'+BB++++++',
'BB+++++++',
'+++++++++',
'+++++++++',
'++WWW++++',
'++W+W++++',
'++WWW++++',
'+++++++++']))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert territory(['++B++++++',
'+BB++++++',
'BB+++++++',
'+++++++++',
'+++++++++',
'++WWW++++',
'++W+W++++',
'++WWW++++',
'+++++++++']) == {'B': 3, 'W': 1}
print("Coding complete? Click 'Check' to earn cool rewards!")
May 25, 2018
Comments: