Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for The Territory of Go by brownie57
def territory(board):
answer = {'B': 0, 'W': 0}
checked = []
stack = []
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == '+' and (i, j) not in checked:
stack.append((i, j))
checked.append((i, j))
count = 0
color = set()
while stack:
y, x = stack.pop(0)
count += 1
for p, q in (y - 1, x), (y, x - 1), (y, x + 1), (y + 1, x):
if 0 <= p < len(board) and 0 <= q < len(board):
if (p, q) not in checked:
if board[p][q] == '+':
stack.append((p, q))
checked.append((p, q))
else:
color.add(board[p][q])
if len(color) == 1:
answer[color.pop()] += count
return answer
if __name__ == '__main__':
print("Example:")
print(territory(['++B++++++',
'+BB++++++',
'BB+++++++',
'+++++++++',
'+++++++++',
'++WWW++++',
'++WWW++++',
'WWWWW++++',
'+W+++++++']))
#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!")
Oct. 26, 2018