graph_search.py 2.3 KB

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