Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for One line Drawing by tarjeii
def draw(segments):
# Make a graph
graph = dict()
for seg in segments:
if seg[:2] in graph:
graph[seg[:2]].add(seg[2:])
else:
graph[seg[:2]] = {seg[2:]}
if seg[2:] in graph:
graph[seg[2:]].add(seg[:2])
else:
graph[seg[2:]] = {seg[:2]}
# Find the nodes with odd number of edges
odd = [x for x in graph.keys() if len(graph[x]) & 1]
odd.append(list(graph.keys())[0])
stack = [odd[0]]
path = []
if len(odd) > 3:
return []
while stack:
next_v = stack[-1]
if next_v in graph:
u = graph[next_v].pop()
stack.append(u)
graph[u].remove(next_v)
# Delete nodes without any edges left
if len(graph[next_v]) == 0:
del graph[next_v]
if len(graph[u]) == 0:
del graph[u]
else:
path.append(stack.pop())
return path
July 31, 2016