Skip to content

Commit e28ca29

Browse files
New commit
1 parent 34cf1a1 commit e28ca29

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

bfs.c

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#include<stdio.h>
2+
#define MAX 100
3+
4+
void addEdge(int u, int v, int adjMatrix[MAX][MAX]){
5+
adjMatrix[u][v] = 1;
6+
adjMatrix[v][u] = 1;
7+
}
8+
9+
void displayMatrix(int nodes, int adjMatrix[MAX][MAX]){
10+
int i,j;
11+
printf("Adjacency Matrix:\n");
12+
for(i=0;i<nodes;i++){
13+
for(j=0;j<nodes;j++){
14+
printf("%d ",adjMatrix[i][j]);
15+
}
16+
printf("\n");
17+
}
18+
}
19+
20+
void BFS(int startNode, int nodes, int adjMatrix[MAX][MAX]){
21+
static int visited[MAX];
22+
int queue[MAX], front = 0, rear = 0, i;
23+
24+
visited[startNode] = 1;
25+
queue[rear++] = startNode;
26+
printf("BFS Traversal starting from from node %d: ",startNode);
27+
28+
while(front!=rear){
29+
int current = queue[front++];
30+
printf("%d ",current+1);
31+
32+
for(i=0;i<nodes;i++){
33+
if(adjMatrix[current][i]==1 && visited[i]==0){
34+
visited[i] = 1;
35+
queue[rear++] = i;
36+
}
37+
}
38+
}
39+
}
40+
41+
int main(){
42+
int i, nodes, edges, u, v;
43+
static int adjMatrix[MAX][MAX];
44+
45+
printf("Enter number of nodes in the graph: ");
46+
scanf("%d", &nodes);
47+
48+
printf("Enter number of edges in the graph: ");
49+
scanf("%d", &edges);
50+
51+
printf("Enter the edges (format: from_node to_node):\n");
52+
for(i=0;i<edges;i++){
53+
scanf("%d %d",&u, &v);
54+
addEdge(u-1, v-1, adjMatrix);
55+
}
56+
57+
displayMatrix(nodes, adjMatrix);
58+
59+
printf("Enter the starting node for BFS traversal: ");
60+
scanf("%d", &u);
61+
62+
BFS(u-1, nodes, adjMatrix);
63+
64+
return 0;
65+
}

bfs.exe

41.7 KB
Binary file not shown.

pattern_1.exe

0 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)