Menu
Coddy logo textTech

Pseudo Code

Lesson 4 of 9 in Coddy's Breadth-First Search - Graph Algorithms course.

bfs(n, edges, start):
   build adjacency (sort each list ascending)
   visited = all false
   queue = [start]; visited[start] = true
   order = []
   while queue not empty:
      node = queue.dequeue()   # take from the FRONT
      order.add(node)
      for nb in adj[node]:
         if not visited[nb]:
            visited[nb] = true
            queue.enqueue(nb)
   return order
  • The only difference from DFS is the container: a queue (FIFO) instead of a stack (LIFO).
  • An easy way to write the queue is an array with a moving head index: dequeue by reading queue[head] and advancing head.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Breadth-First Search - Graph Algorithms