Docsity

Graph Traversals - Data Structures and Algorithms | CS 245, Study notes of Data Structures and Algorithms

Partial preview of the text

Download Graph Traversals - Data Structures and Algorithms | CS 245 and more Study notes Data Structures and Algorithms in PDF only on Docsity!

Data Structures and Algorithms

CS245-2009S-16Graph Traversals

BFS & DFS

David Galles

Department of Computer Science

University of San Francisco

Graph Traversals Visit every vertex, in an order defined by thetopololgy of the graph. Two major traversals:

Depth First Search Breadth First Search

Depth First Search

class Edge {

public int neighbor;public int next;

} void DFS(Edge G[], int vertex, boolean Visited[]) {

Edge tmp;Visited[vertex] = true;for (tmp = G[vertex]; tmp != null; tmp = tmp.next) {

if (!Visited[tmp.neighbor])

DFS(G, tmp.neighbor, Visited);

Depth First Search Example

Visited nodes cicrled in red

Depth First Search Example

Visited nodes cicrled in red

0

DFS(0)
DFS(1)

Depth First Search Example

Visited nodes cicrled in red

0

DFS(0)
DFS(1)^ DFS(3)

Depth First Search Example

Visited nodes cicrled in red

0

DFS(0)
DFS(1)^ DFS(3)
DFS(4)
DFS(2)

Depth First Search Example

Visited nodes cicrled in red

0

DFS(0)
DFS(1)^ DFS(3)
DFS(4)
DFS(2)^ DFS(5)

Depth First Search

To visit every node in the graph: TraverseDFS(Edge G[]) {

int i;boolean Visited = new Edge[G.length];for (i=0; i<G.length; i++)

Visited[i] = false; for (i=0; i<G.length; i++)

if (!Visited[i])

DFS(G, i, Visited);

}

Depth First Search

Examples

DFS & Stacks

Keep track of what nodes we have left using astack Recursive version implicitly uses the system stack Can write DFS non-recursively, using our ownstack

DFS & Stacks

DFS, using recursion

void DFS(Edge G[], int vertex, boolean Visited[]) {

Edge tmp;Visited[vertex] = true;for (tmp = G[vertex]; tmp != null; tmp = tmp.next) {

if (!Visited[tmp.neighbor])

DFS(G, tmp.neighbor, Visited);

Breadth First Search

DFS: Look as

Deep

as possible, before looking

wide

Examine all descendants of a node, beforelooking at siblings BFS: Look as

Wide

as possible, before looking

deep

Visit all nodes 1 away, then 2 away, then threeaway, and so on

Breadth First Search

Examples