Ads La7 - Graph Traversal Using Bfs and Dfs
Ads La7 - Graph Traversal Using Bfs and Dfs
AND DFS
Name: Om Lohade
Class: IT – C
PRN: 12320123
Roll no.: SEDA 3
BFS: BFS is a graph traversal approach in which you start at a source node and
layer by layer through the graph, analyzing the nodes directly related to the
source node. Then, in BFS traversal, you must move on to the next-level
neighbour nodes.
BFS Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 50
int v;
bool adj[MAX][MAX];
}Graph;
Graph *creategraph(int k)
Graph *g = malloc(sizeof(Graph));
g->v=k;
for(int i=0;i<k;i++)
for(int j=0;j<k;j++)
g->adj[i][j]=false;
}
return g;
g->adj[s][d] = true;
free(g);
bool visited[g->v];
visited[j]=false;
int queue[g->v];
int front=0,rear=0;
queue[rear++]=s;
visited[s]=true;
while(front!=rear)
s = queue[front++];
visited[adj]=true;
queue[rear++]=adj;
int main()
// Create a graph
Graph* g = creategraph(4);
createEdge(g, 0, 1);
createEdge(g, 0, 2);
createEdge(g, 1, 2);
createEdge(g, 2, 0);
createEdge(g, 2, 3);
createEdge(g, 3, 3);
BFS(g, 1);
destroy(g);
return 0;
}
DFS Code:
#include <stdio.h>
#include <stdlib.h>
int vis[100];
struct graph
int V;
int E;
int **adj;
};
g->V=7;
g->E=7;
g->adj = (int**)malloc((g->V)*sizeof(int*));
for(int i=0;i<g->V;i++)
{
g->adj[i] = (int*)malloc((g->V)*sizeof(int));
for(int j=0;j<g->V;j++)
for(int k=0;k<g->V;k++)
g->adj[j][k]=0;
g->adj[0][1] = g->adj[1][0] = 1;
g->adj[0][2] = g->adj[2][0] = 1;
g->adj[1][3] = g->adj[3][1] = 1;
g->adj[1][4] = g->adj[4][1] = 1;
g->adj[1][5] = g->adj[5][1] = 1;
g->adj[1][6] = g->adj[6][1] = 1;
g->adj[6][2] = g->adj[2][6] = 1;
return g;
vis[u]=1;
DFS(g,v);
{
for(int p=0;p<100;p++)
vis[p]=0;
for(int q=0;q<g->V;q++)
if(!vis[q])
DFS(g,q);
void main()
struct Graph* G;
G = adj();
DFStraversal(G);