here are my python code for dfs path search:
class Graph(object):
def __init__(self,dict=None):
Graph.node = dict if dict != None else {}
def add_node(self,nodedict):
self.node = dict(self.node,**nodedict)
def traversal_dfs(self,start,target,path = []):
path = path + [start]
for vertex in self.node[start]:
print path,vertex,target
if vertex == target:
return path + [vertex]
elif vertex not in path:
path = self.traversal_dfs(vertex,target,path)
if __name__ == "__main__":
g = Graph({'a':['b','c'],'b':['c','e'],'c':['d'],'d':['e'],'e':['f','a'],'f':['b']})
print g.traversal_dfs('a','f')
But when I run it, I got errors like that:
Traceback (most recent call last):
File "/Users/zzzyui/PycharmProjects/python_test/Traversal.py", line 25, in <module>
['a'] b f
print g.traversal_dfs('a','f')
['a', 'b'] c f
['a', 'b', 'c'] d f
['a', 'b', 'c', 'd'] e f
File "/Users/zzzyui/PycharmProjects/python_test/Traversal.py", line 19, in traversal_dfs
['a', 'b', 'c', 'd', 'e'] f f
path = self.traversal_dfs(vertex,target,path)
stop flag
None e f
File "/Users/zzzyui/PycharmProjects/python_test/Traversal.py", line 18, in traversal_dfs
elif vertex not in path:
TypeError: argument of type 'NoneType' is not iterable
I wonder why the condition vertex == target does not work and how to fix it?