Graph Search Methods: U V V U
Graph Search Methods: U V V U
3
8
9 10
11
3
8
9 10
11
Depth-First Search
DFS(v) { Label vertex v as reached. for (each unreached vertex u adjacenct from v) DFS(u); }
9 10
11
Start search at vertex 1. Label vertex 1 and do a depth first search from either 2 or 4. Suppose that vertex 2 is selected.
1
5
9 10
11
1
5
9 10
11
Label vertex 5 and do a depth first search from either 3, 7, or 9. Suppose that vertex 9 is selected.
1
5
9 10
11
Label vertex 9 and do a depth first search from either 6 or 8. Suppose that vertex 8 is selected.
1
5
9 10
11
1
5
9 10
11
1
5
9 10
11
1
5
9 10
11
Return to 9.
1
5
9 10
11
Return to 5.
1
5
9 10
11
Do a DFS(3).
1
5
9 10
11
1
5
9 10
11
Return to 1.
1
5
9 10
11
Connected Components
Start a depth-first search at any as yet unvisited vertex of the graph. Newly visited vertices (plus edges between them) define a component. Repeat until all vertices are visited.
Connected Components
2 1 4 5 3 8
9 10
11
Time Complexity
O(n2) when adjacency matrix used O(n+e) when adjacency lists used (e is number of edges)
Spanning Tree
2 1 4 5 3
Spanning Tree
Start a depth-first search at any vertex of the graph. If graph is connected, the n-1 edges used to get to unvisited vertices define a spanning tree (depth-first spanning tree). Time
O(n2) when adjacency matrix used O(n+e) when adjacency lists used (e is number of edges)
Breadth-First Search
Visit start vertex and put into a FIFO queue. Repeatedly remove a vertex from the queue, visit its unvisited adjacent vertices, put newly visited vertices into the queue.
9 10
11
FIFO Queue
1
9 10
11
FIFO Queue
1
9 10
11
FIFO Queue 2 4
9 10
11
FIFO Queue 2 4
9 10
11
FIFO Queue 4 5 3 6
9 10
11
FIFO Queue 4 5 3 6
9 10
11
FIFO Queue 5 3 6
9 10
11
FIFO Queue 5 3 6
9 10
11
FIFO Queue 3 6 9 7
9 10
11
FIFO Queue 3 6 9 7
9 10
11
FIFO Queue 6 9 7
9 10
11
FIFO Queue 6 9 7
9 10
11
FIFO Queue 9 7
9 10
11
FIFO Queue 9 7
9 10
11
FIFO Queue 7 8
9 10
11
FIFO Queue 7 8
9 10
11
FIFO Queue 8
9 10
11
FIFO Queue 8
9 10
11
FIFO Queue
9 10
11
Time Complexity
Each visited vertex is put on (and so removed from) the queue exactly once. When a vertex is removed from the queue, we examine its adjacent vertices.
O(n) if adjacency matrix used O(vertex degree) if adjacency lists used
Total time
O(mn), where m is number of vertices in the component that is searched (adjacency matrix)
Time Complexity
O(n + sum of component vertex degrees) (adj. lists) = O(n + number of edges in component)