ECS110 Lecture Notes for Wednesday, November 22, 1995
Professor Rogaway conducting
Lecture 22
Scribe of the day: Joe McCarthy
TODAY: Depth First Traversal of a graph
Breadth First Traversal of a graph
-------------------------------------------------------------------------
Depth First Traversal of a graph:
5 ADJACENCY LIST:
| 0: 1
| 1: 0,2,3,7
4---2---3 2: 1,3,4,7
/ \ |\ /| 3: 1,2,7
/ \ |/ \| 4: 2,5,6,7
6 7---1 5: 4
| 6: 4
| 7: 1,2,3,4
0
Above graph: start vertex v=6 or DFS(6)
nodes visited in order: 6,4,2,1,0,3,7,5
Depth First Search(DFS):
-decides connectivity
-provides DFS numbering
-computes a spanning tree
Begin DFS by first visiting the start vertex v. Next, an unvisited
vertex w adjacent to v is selected and a DFS from w is initiated.
When a vertex u is reached such that all its adjacent verticies have
been visited, back up to the last vertex visited that has an
unvisited vertex w adjacent to it and initiate a DFS from w. The
search terminates when no unvisited vertex can be reached from any
of the visited verticies.
IMPLEMENTATION:
for each w in V: VISITED[w] = 0; //initializes the search
DFS(v) // v is the start vertex
VISIT(v); VISITED[v] = 1;
for every w in Adj[v]
if(! VISITED[w])
DFS(w);
------------------------------------------------------------------------
Breadth First Search Traversal of a graph
5
|
|
4---2---3
/ \ |\ /|
/ \ |/ \|
6 7 1
|
|
0
order of visitation, BFS(6): 6,4,2,5,7,1,3,0
an array is used to keep track of which nodes have been visited
queue representation: enqueue a node's adjacent nodes
(that aren't already in the queue)
dequeue a node that has been visited
example for BFS(6):
front of queue-> 6 (enqueue 6)
-> 4 (dequeue 6, enqueue 4)
-> 2,5,7 (dequeue 4, enqueue 2,5,7)
-> 5,7,1,3 (dequeue 2, enqueue 1,3)
-> 7,1,3 (dequeue 5)
-> 1,3 (dequeue 7)
-> 3,0 (dequeue 1, enqueue 0)
-> 0 (dequeue 3)
-> (dequeue 0)--DONE
Breadth First Search(BFS):
Begin by visiting the start vertex v. Next, all unvisited verticies
adjacent to v are visited. Unvisited verticies adjacent to these
newly visited verticies are then visited, and so on.
IMPLEMENTATION:
BFS(v)
for each w in V, visited[w]=0;
Queue q;
q.insert(v); visited[v]=1;
while(! q.empty())
v<-q.dequeue();
VISIT(v);
for each w in Adj[v]
if(! visited[w])
{
q.insert(w);
visited[w]=1;
}
----------------------------------------------------------------------------
Time Bounds
DFS & BFS: O(n+m) time (n=verticies, m=edges)
same as O(m)--graph connected
O(m) space