Graph Searching
(JAVA)
Hira Awais
Lecturer (DCS)
DDSA (FOC)
Slide courtesy: Dr. Zahid Halim
Graph Searching
Given: a graph G = (V, E), directed or undirected
Goal: methodically explore every vertex and every edge
Ultimately: build a tree on the graph
Pick a vertex as the root
Choose certain edges to produce a tree
Breadth-First Search
Given a G=(V,E) and distinguished source vertex s, BFS systematically
explores the edges of G to “discover” every vertex reachable from s.
Creates a BFS tree rooted at s that contains all such vertices.
Expands the frontier between discovered and undiscovered vertices
uniformly across the breadth of the frontier.
The algorithm discovers all vertices at distance k from s before discovering
any vertices at distance k+1
Breadth-First Search
will associate vertex “colors” to guide the algorithm
White vertices have not been discovered
▪ All vertices start out white
Grey vertices are discovered but not fully explored
▪ They may be adjacent to white vertices and represent the frontier between the discovered and the
undiscovered.
Black vertices are discovered and fully explored
▪ They are adjacent only to black and gray vertices
Explore vertices by scanning adjacency list of grey vertices
Breadth-First Search – Pseudo Code
1. BFS(G, s) {
2. initialize vertices;
3. Q = {s}; // Q is a queue initialize to s
4. while (Q not empty) {
5. u = Dequeue(Q);
6. for each v u->adj {
7. if (v->color == WHITE){
8. v->color = GREY;
9. v->d = u->d + 1;
10. v->p = u;
11. Enqueue(Q, v);
12. }
13. }
14. u->color = BLACK;
15. }
16. }
Breadth-First Search - Example
r s t u
v w x y
Breadth-First Search: Example
r s t u
0
v w x y
Q: s
Breadth-First Search: Example
r s t u
1 0
1
v w x y
Q: w r
Breadth-First Search: Example
r s t u
1 0 2
1 2
v w x y
Q: r t x
Breadth-First Search: Example
r s t u
1 0 2
2 1 2
v w x y
Q: t x v
Breadth-First Search: Example
r s t u
1 0 2 3
2 1 2
v w x y
Q: x v u
Breadth-First Search: Example
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: v u y
Breadth-First Search: Example
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: u y
Breadth-First Search: Example
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: y
Breadth-First Search: Example
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: Ø
Breadth-First Search: Properties
BFS calculates the shortest-path distance to the source node
Shortest-path distance (s,v) = minimum number of edges from s to
v, or if v not reachable from s
BFS builds breadth-first tree, in which paths to root represent
shortest paths in G
Thus can use BFS to calculate shortest path from one vertex to
another in O(V+E) time
Applications of BFS
Web Crawlers
Search engines or web crawlers can easily build multiple levels of indexes by
employing BFS. BFS implementation starts from the source, which is the web
page, and then it visits all the links from that source.
P2P Networks
BFS can be implemented to locate all the nearest or neighboring node in a P2P
network. This will find the required data faster.
Un-weighted graph
BFS can easily create the shortest path and minimum spanning tree to visit all
the vertices of the graph in the shortest possible time with high accuracy.
Depth First Search
Depth-first search: Strategy Go as deep as can visiting un-visited
nodes
Choose any un-visited vertex when you have a choice
When stuck at a dead-end, backtrack as little as possible back up
to where you could go to another unvisited vertex
Then continue to go on from that point
Eventually you’ll return to where you started
DFS Algorithm
DFS(G)
for each vertex u V[G]{
color[u]=white
parent[u]=NULL
}
time=0
for each vertex u V[G]{
if color[u]=white then
DFS-VISIT(u)
}
DFS-VISIT(u)
color[u]=GRAY
time=time+1
d[u]=time
for each vertex v adj[u] {
if color[v]=white Then
parent[v]=u
DFS-VISIT(v)
}
color[u]=black
f[u]=time=time+1
DFS [Easy One]
1. Initialize all nodes to the ready state (STATUS=1)
2. PUSH starting node A on stack and change its status to waiting(STATUS=2)
3. Repeat 4-5 until stack is empty
4. POP N. Process it and change its status to processed(STATUS=3)
5. PUSH on stack all the neighbors of N that are still in ready state and
change their status to waiting
6. Exit
Depth-First Search - Example
Depth-First Search - Example
Depth-First Search - Example
Depth-First Search - Example
Depth-First Search - Example
Depth-First Search - Example
Applications of DFS
Path finding
We can specialize in DFS algorithm to search a path between two
vertices
Detecting a cycle in a graph
A graph has a cycle if we found a back edge during DFS. Therefore, we
should run DFS for the graph and verify for back edges.
Weighted graph
DFS traversal generates the shortest path tree and minimum spanning
tree
BFS VS. DFS
Breadth-First Search Depth-First Search
Find the shortest path to the destination or closet node Finds the longest path or the farthest node to the
to the starting node starting node
Uses queue to keep track of the next location to visit Uses stack to keep track of the next location to visit
Traverses according to tree level Traverses according to tree depth
Implement using FIFO list Implement using LIFO list
Require more memory than DFS Requires less memory than BFS
Algorithm gives shallowest path solution Does not guarantee shallowest path solution
Can never trap in infinite loop Can trap in infinite loop
No need of back tracking Back tracking is needed
Why BFS takes more memory than DFS?
BFS is more memory-intensive than DFS, as it needs to store all
the nodes at each level, while DFS only needs to store the
current path
Difference between BFS & DFS
BFSis more likely to find a solution faster than DFS, if there is
one, as it explores all possible paths at each level while DFS
may get stuck in a dead end or a cycle.
BFS is more predictable than DFS, as it always visits the nodes
in the same order, while DFS may vary depending on the order
of edges.
How to choose between BFS & DFS for a
problem?
Structure and size of the graph
Location & number of the nodes of interest
Type and complexity of the problem
Memory & time constraint