12th Done
12th Done
Date of Performance:
Date of Submission:
Aim: Implement Graph Traversal techniques : a) Depth First Search (DFS) b) Breadth
First Search(BFS).
Theory:
Graph traversal is a technique used for a searching vertex in a graph. The graph traversal is also
used to decide the order of vertices is visited in the search process. A graph traversal finds the
edges to be used in the search process without creating loops. That means using graph traversal we
visit all the vertices of the graph without getting into looping path.
There are two graph traversal techniques and they are as follows.
1. DFS (Depth First Search)
2. BFS (Breadth First Search)
Algorithms: DFS
Back tracking is coming back to the vertex from which we reached the current vertex.
Example: DFS
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.
After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have
completed the Depth First Traversal of the graph.
Example: BFS
Let's see how the Breadth First Search algorithm works with an example. We use an undirected
graph with 5 vertices.
We start from vertex 0, the BFS algorithm starts by putting it in the Visited list and putting all its
adjacent vertices in the stack.
Visit start vertex and add its adjacent vertices to queue
Next, we visit the element at the front of queue i.e. 1 and go to its adjacent nodes. Since 0 has
already been visited, we visit 2 instead.
Visit last remaining item in the queue to check if it has unvisited neighbors
Since the queue is empty, we have completed the Breadth First Traversal of the graph.
#include <conio.h>
int vis[10] = {0}, vertices, edge[10][10] = {0}, neighbour, i, j, noe, q[10], front = 0, rear = 0,
size = 0;
vis[node] = 1;
q[rear] = node;
size++;
while (size != 0) {
size--;
printf("%d\n", removed);
vis[neighbour] = 1;
q[rear] = neighbour;
size++;
}
}
void display() {
printf("Adjacency Matrix:\n");
printf("\n");
void main() {
clrscr();
vertices = 4;
bfs(0);
display();
getch();
OUTPUT :
#include <stdio.h>
#include <conio.h>
printf("%d\n", node);
vis[node] = 1;
DFS(neighbour);
void main() {
int v, u;
clrscr();
scanf("%d", &vertices);
printf("enter number of edges:\n");
scanf("%d", &noe);
edge[u][v] = 1;
edge[v][u] = 1;
// if (!vis[i]) {
// DFS(i);
// }
// }
DFS(0);
getch();
OUTPUT :
Conclusion: