Graphs and Traversal

Computer Science & Algorithms · Advanced Placement

Graphs and their size

{{illustration:cg-edges}}

- A graph has n vertices and m edges; m ranges from 0 to n(n − 1)/2. - Sparse graphs have m close to n.

Representations

{{illustration:cg-repr}}

| Representation | Space | Edge test | List neighbours | |---|---|---|---| | adjacency matrix | n² | 1 | n | | adjacency list | n + 2m | degree | degree | | edge list | m | m | m |

Breadth-first search

{{illustration:cg-bfs}}

- Uses a queue and explores by distance. - Runs in Θ(n + m).

Depth-first search and levels

{{illustration:cg-levels}}

- DFS uses a stack or recursion and goes deep first. - Both give connected components in Θ(n + m).