# encoding: utf-8
# A linha anterior permite usar acentos no nosso programa.
def gerar_caminhos(grafo, caminho, final):
"""Enumera todos os caminhos no grafo `grafo` iniciados por `caminho` e que terminam no vértice `final`."""
# Se o caminho de fato atingiu o vértice final, não há o que fazer.
if caminho[-1] == final:
yield caminho
return
# Procuramos todos os vértices para os quais podemos avançar…
for vizinho in G[caminho[-1]]:
# …mas não podemos visitar um vértice que já está no caminho.
if vizinho in caminho:
continue
# Se você estiver usando python3, você pode substituir o for
# pela linha "yield from gerar_caminhos(grafo, caminho + [vizinho], final)"
for caminho_maior in gerar_caminhos(grafo, caminho + [vizinho], final):
yield caminho_maior
# Exemplo de uso
G = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], 'C': ['A', 'B', 'D'], 'D': ['B', 'C']}
for caminho in gerar_caminhos(G, ['A'], 'D'):
# "print(caminho)" em python3
print caminho
IyBlbmNvZGluZzogdXRmLTgKIyBBIGxpbmhhIGFudGVyaW9yIHBlcm1pdGUgdXNhciBhY2VudG9zIG5vIG5vc3NvIHByb2dyYW1hLgoKZGVmIGdlcmFyX2NhbWluaG9zKGdyYWZvLCBjYW1pbmhvLCBmaW5hbCk6CiAgICAiIiJFbnVtZXJhIHRvZG9zIG9zIGNhbWluaG9zIG5vIGdyYWZvIGBncmFmb2AgaW5pY2lhZG9zIHBvciBgY2FtaW5ob2AgZSBxdWUgdGVybWluYW0gbm8gdsOpcnRpY2UgYGZpbmFsYC4iIiIKCiAgICAjIFNlIG8gY2FtaW5obyBkZSBmYXRvIGF0aW5naXUgbyB2w6lydGljZSBmaW5hbCwgbsOjbyBow6EgbyBxdWUgZmF6ZXIuCiAgICBpZiBjYW1pbmhvWy0xXSA9PSBmaW5hbDoKICAgICAgICB5aWVsZCBjYW1pbmhvCiAgICAgICAgcmV0dXJuCgogICAgIyBQcm9jdXJhbW9zIHRvZG9zIG9zIHbDqXJ0aWNlcyBwYXJhIG9zIHF1YWlzIHBvZGVtb3MgYXZhbsOnYXLigKYKICAgIGZv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