Graph Searching - Java
Graph Searching - Java
Hira Awais
Lecturer (DCS)
DDSA (FOC)
Slide courtesy: Dr. Zahid Halim
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
Given a G=(V,E) and distinguished source vertex s, BFS systematically
explores the edges of G to “discover” every vertex reachable from s.
v w x y
r s t u
0
v w x y
Q: s
r s t u
1 0
1
v w x y
Q: w r
r s t u
1 0 2
1 2
v w x y
Q: r t x
r s t u
1 0 2
2 1 2
v w x y
Q: t x v
r s t u
1 0 2 3
2 1 2
v w x y
Q: x v u
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: v u y
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: u y
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: y
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: Ø
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
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: Strategy Go as deep as can visiting un-visited
nodes
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
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
Path finding
We can specialize in DFS algorithm to search a path between two
vertices
Weighted graph
DFS traversal generates the shortest path tree and minimum
spanning tree
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
Require more memory than DFS Requires less memory than BFS
Algorithm gives shallowest path solution Does not guarantee shallowest path solution