graph_search.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. class GraphSearch:
  2. """Graph search emulation in python, from source http://www.python.org/doc/essays/graphs/"""
  3. def __init__(self, graph):
  4. self.graph = graph
  5. def find_path(self, start, end, path=[]):
  6. self.start = start
  7. self.end = end
  8. self.path = path
  9. self.path+=[self.start]
  10. if self.start == self.end:
  11. return self.path
  12. if not self.graph.has_key(self.start):
  13. return None
  14. for node in self.graph[self.start]:
  15. if node not in self.path:
  16. newpath = self.find_path(node, self.end, self.path)
  17. if newpath:
  18. return newpath
  19. return None
  20. def find_all_path(self, start, end, path=[]):
  21. self.start = start
  22. self.end = end
  23. self.path = path
  24. self.path+=[self.start]
  25. if self.start == self.end:
  26. return [self.path]
  27. if not self.graph.has_key(self.start):
  28. return []
  29. paths=[]
  30. for node in self.graph[self.start]:
  31. if node not in self.path:
  32. newpaths = self.find_all_path(node, self.end, self.path)
  33. for newpath in newpaths:
  34. paths.append(newpath)
  35. return paths
  36. def find_shortest_path(self, start, end, path=[]):
  37. self.start = start
  38. self.end = end
  39. self.path = path
  40. self.path+=[self.start]
  41. if self.start == self.end:
  42. return self.path
  43. if not self.graph.has_key(self.start):
  44. return None
  45. shortest = None
  46. for node in self.graph[self.start]:
  47. if node not in self.path:
  48. newpath = self.find_shortest_path(node, self.end, self.path)
  49. if newpath:
  50. if not shortest or len(newpath) < len(shortest):
  51. shortest = newpath
  52. return shortest
  53. #example of graph usage
  54. graph = {'A':['B', 'C'],
  55. 'B': ['C', 'D'],
  56. 'C': ['D'],
  57. 'D': ['C'],
  58. 'E': ['F'],
  59. 'F': ['C']
  60. }
  61. #inistialization of new graph search object
  62. graph1 = GraphSearch(graph)
  63. print graph1.find_path('A', 'D')
  64. print graph1.find_all_path('A', 'D')
  65. print graph1.find_shortest_path('A', 'D')