teacher
Sign in

Graphs, BFS and DFS

Store a graph as adjacency lists, find shortest paths on unweighted graphs and grids with BFS, and count components, detect cycles and 2-colour with DFS.

50 minCF 1200–17008 interactive10 problems

The problem

A graph is a set of nodes (also called vertices) joined by edges. An edge can be undirected (works both ways, like a road) or directed (one way, like a link between web pages). Cities and roads, friends in a network, cells of a maze and "task A must come before task B" are all graphs.

Questions that come up again and again:

  • Can I get from node aa to node bb?
  • What is the fewest number of edges on a path from aa to bb?
  • How many separate pieces (connected components) does the graph have?
  • Is there a cycle (a path that returns to its start)?
  • Can the nodes be split into two groups with every edge going between the groups (bipartite)?

Notation: nn nodes, mm edges.

1 of 10