你的代码太复杂了。
从只实现基础的代码开始,然后逐渐添加功能。为了让您入门,我将在处理图表时发布一些简单但基本的内容。
from collections import deque
class fringe(object):
def __init__(self, kind= 'stack'):
f= deque()
self._p= f.append if kind is 'stack' else f.appendleft
self._f= f
def __call__(self, item):
self._p(item)
return self
def __iter__(self):
while len(self._f):
item= self._f.pop()
yield item
def __repr__(self):
return self._f.__repr__().replace('deque', 'fringe')
def paths(G, start, terminal, F= fringe()):
for node, path in F((start, [start])):
for node in G[node]:
if node is terminal:
yield path+ [terminal]
elif node not in path:
F((node, path+ [node]))
和一个测试:
if __name__ == '__main__':
a, b, c, d, e, f= 'A', 'B', 'C', 'D', 'E', 'F'
G= {a: [b, c], b: [c, d], c: [d], d: [c], e: [f], f: [c]}
print 'All paths from:', a, 'to:', d
print 'BFS'
for path in paths(G, a, d): print path
print 'DFS'
for path in paths(G, a, d, fringe('queue')): print path
运行将产生:
All paths from: A to: D
BFS
['A', 'C', 'D']
['A', 'B', 'D']
['A', 'B', 'C', 'D']
DFS
['A', 'B', 'D']
['A', 'C', 'D']
['A', 'B', 'C', 'D']