Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
depth-first search solution in Clear category for The Buttons by David_Jones
def buttons(ceiling):
ceiling = ceiling.strip().splitlines()
n, m = len(ceiling), len(ceiling[0])
figure_values = []
used = set()
for i in range(n):
for j in range(m):
if ceiling[i][j] > '0' and (i,j) not in used:
figure_value = 0
stack = [(i,j)]
while stack:
x, y = stack.pop()
if (x,y) not in used:
used.add((x,y))
figure_value += int(ceiling[x][y])
for a, b in ((x-1,y), (x,y-1), (x,y+1), (x+1,y)):
if (
0 <= a < n and 0 <= b < m
and ceiling[a][b] > '0' and (a,b) not in used
):
stack.append((a,b))
figure_values.append(figure_value)
return sorted(figure_values, reverse=True)
May 21, 2019