Graph Searching - Java
Graph Searching - Java
(JAVA)
Hira Awais
Lecturer (DCS)
DDSA (FOC)
Slide courtesy: Dr. Zahid Halim
Graph Searching
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
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
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
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
Require more memory than DFS Requires less memory than BFS
Algorithm gives shallowest path solution Does not guarantee shallowest path solution