Last active
August 29, 2015 13:56
-
-
Save SamuraiT/9318649 to your computer and use it in GitHub Desktop.
Breadth-first-search implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RandomGraph(Graph): | |
def bfs(self, v): | |
"""search graph by a BFS: breadth-first-search""" | |
worklist = [v] | |
closed = [] | |
while worklist: # order of growth is O(n) | |
visited = worklist.pop(0) # O(n) | |
closed.append(visited) # | |
vs = self.out_vertices(visited) | |
vs = [v for v in vs if not (v in closed or v in worklist)] # ~O(n) | |
worklist.extend(vs) | |
return closed | |
def better_bfs(self, v): | |
"""order of growth is linear: O(n)""" | |
worklist = deque([v]) | |
closed = set() | |
while worklist: # order of growth is O(n) | |
visited = worklist.popleft() # O(1) | |
if visited in closed:continue | |
closed.add(visited) | |
vs = self.out_vertices(visited) | |
worklist.extend(vs) | |
return closed | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment