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.
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 to node ?
- What is the fewest number of edges on a path from to ?
- 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: nodes, edges.
1 of 10