FIFO Queue
Used by BFS
Like a line at a coffee shop - first person in line gets served first. BFS uses this to explore all neighbors at depth 1, then all at depth 2, etc.
class FIFOQueue:
def __init__(self):
self.q = deque()
def push(self, x):
self.q.append(x) # enqueue
def pop(self):
return self.q.popleft() # dequeue (front)
def empty(self):
return not self.q
LIFO Stack
Used by DFS
Like a stack of plates - you take from the top (last one added). DFS uses this to dive deep into one path before exploring alternatives.
class LIFOStack:
def __init__(self):
self.s = []
def push(self, x):
self.s.append(x) # push top
def pop(self):
return self.s.pop() # pop top
def empty(self):
return not self.s
Min-Heap PQ
Used by UCS
Like an emergency room - patients with most urgent (lowest) priority numbers get treated first. UCS uses this to always expand the node with the lowest path cost.
class MinHeapPQ:
def __init__(self):
self.h = []
def push(self, priority, item):
heapq.heappush(self.h, (priority, item))
def pop(self):
priority, item = heapq.heappop(self.h)
return priority, item
def empty(self):
return not self.h