Graphs

Problem shape

Beginner
A
B
C
D
E
Core idea

Visit nodes level by level with a queue.

Step 1 / 5
Problem shape
Current lesson

Breadth-First Search Lab

Graphs Beginner

Breadth-First Search

Welcome to the Breadth-First Search algorithm lab. Visit nodes level by level with a queue. Use it when: Use for shortest paths in unweighted graphs and level-order traversal. The time complexity is O(V + E), and the space complexity is O(V). The pseudocode is: queue.push(start) mark start while queue not empty node = queue.pop() for next in graph[node] if not seen next mark next queue.push(next) As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(V + E)

Space

O(V)

Pseudocode

queue.push(start)
mark start
while queue not empty
  node = queue.pop()
  for next in graph[node]
    if not seen next
      mark next
      queue.push(next)
Open deeper structure lesson
1.0x