plan cs 312: bfs and dfs implementation
TRANSCRIPT
CS 312: BFS and DFS implementation
Dan Sheldon
February 10, 2015
Plan
I Generic Graph Traversal
I Graph Data Structure: Adjacency Lists
I Directed Graphs and Toplogical Sort
Generic Graph Traversal
Maintain set of explored nodes and discovered
I Explored = have seen this node and explored all of its outgoingedges
I Discovered = the “frontier”. Have seen the node, but notexplored its outgoing edges.
Picture on board
Generic Graph Traversal: Node Version
Let A = data structure of discovered nodes
Traverse(s)
Put s in Awhile A is not empty do
Take a node v from Aif v is not marked ”explored” then
Mark v as ”explored”for each edge (v, w) incident to v do
Put w in Aend for
end if
end while
BFS: A is a queue (LIFO)DFS: A is a stack (LIFO)
Generic Graph Traversal
Let A = data structure of discovered nodes
Traverse(s)
Put s in Awhile A is not empty do
Take a node v from Aif v is not marked ”explored” then
Mark v as ”explored”for each edge (v, w) incident to v do
Put w in Aend for
end if
end while
BFS: A is a queue (FIFO)DFS: A is a stack (LIFO)
Examples
“Proof by example”
I BFS with queue
I DFS with stack
Generic Graph Traversal: Edge Version
To return a tree, put edges instead of nodes on TODO list
Traverse(s)
T = {} . BFS/DFS treePut (�, s) in Awhile A is not empty do
Take an edge (u, v) from Aif v is not marked ”explored” then
T = T [ (u, v)Mark v as ”explored”for each edge (v, w) incident to v do
Put edge (v, w) in Aend for
end if
end while
Return T
Running Time?
Traverse(s)
Put s in Awhile A is not empty do
Take a node v from Aif v is not marked ”explored” then
Mark v as ”explored”for each edge (v, w) incident to v do
Put w in Aend for
end if
end while
Discuss on board. Running time is O(m+ n), pending correct datastructure
n2m
2m2m
2m
2m
Representing Graphs: Adjacency List
Adjacency list. Each node keeps a (linked) list of neighbors.!
How long to find a specific edge?!How long to find all edges incident on a node?
1
3
5 4
21
2
3
4
5
2 4 5
1 3 4
2 5
1 2
1 3
Graph Traversal: Summary
BFS/DFS: O(m+ n)
I Is G connected?I Find connected components of GI Find distance of every vertex from sourceI Get BFS/DFS trees (useful in other applications)
BFS: explore by distance; layers; queueDFS: explore deeply; recursive; stack