Graph Treversal (BFS-DFS) Unit 5
Graph Treversal (BFS-DFS) Unit 5
Unit No. 6
Prepared By:
Mr. Zeeshan Mubeen (Senior Lecturer, Superior)
Graph
• A Graph is a non-linear data structure consisting of nodes and
edges. The nodes are sometimes also referred to as vertices
and the edges are lines or arcs that connect any two nodes in
the graph.
Undirected Graph
Graph 1:
V = {A, B, C, D, E, F}
E = {(A, B), (A, C), (B, C), (B, D), (D, E), (D, F), (E, F)}
Directed Graph
• The order in which the vertices are visited are important and
may depend upon the algorithm or question that you are
solving.
• First move horizontally and visit all the nodes of the current
layer
• Move to the next layer
BFS Diagram
Traversing process
Traversing process
Traversing process
Breadth First Search (BFS)
Pseudocode:
• BFS (G, s) //Where G is the graph
and s is the source node
• Let Q be queue.
• Q.enqueue( s ) //Inserting s in queue until
all its neighbor vertices are marked.
• mark s as visited.
Stack
Continue..
Stack
Depth-first search (DFS)
pseudocode:
• DFS(G,v) ( v is the vertex where the search
starts )
• Stack S := {}; ( start with an empty stack )
• for each vertex u, set visited[u] := false;
• push S, v;
• while (S is not empty) do
• u := pop S;
• if (not visited[u]) then
• visited[u] := true;
• for each unvisited neighbor w of u
• push S, w;
• end if
• end while
• END DFS()