Skip to content

Instantly share code, notes, and snippets.

@daryl314
Created January 8, 2019 14:21
Show Gist options
  • Save daryl314/1a402ee340bc14d02663c816e986fb88 to your computer and use it in GitHub Desktop.
Save daryl314/1a402ee340bc14d02663c816e986fb88 to your computer and use it in GitHub Desktop.
BFS search queue in python
from collections import deque
class SearchQueue(object):
"""BFS search queue"""
def __init__(self, seeds=[]):
"""Initialize with an optional list of seeds"""
self.Q = deque()
self.explored = set()
self.pushAll(seeds)
def __len__(self):
"""Number of items in queue"""
return len(self.Q)
def __iter__(self):
"""Return a SearchQueue iterator (SearchQueue itself)"""
return self
def __next__(self):
"""Return next item for iteration"""
if len(self) == 0:
raise StopIteration
else:
return self.pop()
def next(self):
"""Delegate to __next__ for python2 support"""
return self.__next__()
def pop(self):
"""Pop the next item off the queue"""
return self.Q.popleft()
def push(self, seed):
"""Push an item onto the queue if it has not been seen yet"""
if seed not in self.explored:
self.Q.append(seed)
self.explored.add(seed)
def pushAll(self, seeds):
"""Push unseen items from a collection onto the queue"""
for seed in seeds:
self.push(seed)
if __name__ == '__main__':
G = {'A':{'B','C','D'},'B':{'E'},'C':{'E','F'},'D':{'F'},'E':{'G','H'},'F':{'H','I'},'G':[],'H':[],'I':[]}
Q = SearchQueue(['A'])
for node in Q:
print(node)
Q.pushAll(G[node])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment