Skip to content

clean up graph search #152

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 23, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 22 additions & 36 deletions graph_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,53 +11,39 @@ def __init__(self, graph):
self.graph = graph

def find_path(self, start, end, path=None):
self.start = start
self.end = end
self.path = path if path else []
path = path or []

self.path += [self.start]
if self.start == self.end:
return self.path
if self.start not in self.graph:
return None
for node in self.graph[self.start]:
if node not in self.path:
newpath = self.find_path(node, self.end, self.path)
path.append(start)
if start == end:
return path
for node in self.graph.get(start, []):
if node not in path:
newpath = self.find_path(node, end, path)
if newpath:
return newpath
return None

def find_all_path(self, start, end, path=None):
self.start = start
self.end = end
_path = path if path else []
_path += [self.start]
if self.start == self.end:
return [_path]
if self.start not in self.graph:
return []
path = path or []
path.append(start)
if start == end:
return [path]
paths = []
for node in self.graph[self.start]:
if node not in _path:
newpaths = self.find_all_path(node, self.end, _path[:])
for newpath in newpaths:
paths.append(newpath)
for node in self.graph.get(start, []):
if node not in path:
newpaths = self.find_all_path(node, end, path[:])
paths.extend(newpaths)
return paths

def find_shortest_path(self, start, end, path=None):
self.start = start
self.end = end
_path = path if path else []
path = path or []
path.append(start)

_path += [self.start]
if self.start == self.end:
return _path
if self.start not in self.graph:
return None
if start == end:
return path
shortest = None
for node in self.graph[self.start]:
if node not in _path:
newpath = self.find_shortest_path(node, self.end, _path[:])
for node in self.graph.get(start, []):
if node not in path:
newpath = self.find_shortest_path(node, end, path[:])
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
Expand Down