Loading…
DAA · Graphs · Program 20 · In the record
Write a program in c to traverse a graph using breadth first search (BFS) and find its execution time using the time function.
Algorithm: BFS(G, s) 1. Start 2. For each vertex u in G do 3. visited[u] <- 0 4. d[u] <- infinity 5. visited[s] <- 1, d[s] <- 0 6. Enqueue(Q, s) 7. While Q is not empty do 8. u <- Dequeue(Q) 9. print u 10. For each vertex v adjacent to u do 11. if visited[v] == 0 then 12. visited[v] <- 1 13. d[v] <- d[u] + 1 14. Enqueue(Q, v) 15. Stop
1#include<stdio.h>2#include<time.h>3 4int main() {5 int n,i,u,v,s,front=0,rear=0,count=0;6 printf("Enter the number of vertices:");7 scanf("%d",&n);8 int adj[n+1][n+1],visited[n+1],d[n+1],Q[n];9 printf("Enter the %dx%d adjacency matrix:\n",n,n);10 for(u=1;u<=n;u++)11 for(v=1;v<=n;v++)12 scanf("%d",&adj[u][v]);13 printf("Enter the source vertex:");14 scanf("%d",&s);15 16 clock_t start=clock();17 for(u=1;u<=n;u++) {18 visited[u]=0;19 d[u]=-1;20 }21 visited[s]=1;22 d[s]=0;23 Q[rear++]=s;24 printf("\nBFS traversal:");25 while(front<rear) {26 u=Q[front++];27 printf("\t%d",u);28 for(v=1;v<=n;v++) {29 count++;30 if(adj[u][v]==1 && visited[v]==0) {31 visited[v]=1;32 d[v]=d[u]+1;33 Q[rear++]=v;34 }35 }36 }37 clock_t end=clock();38 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;39 40 printf("\nVertex\tDistance from %d",s);41 for(i=1;i<=n;i++)42 if(d[i]==-1)43 printf("\n%d\tunreachable",i);44 else45 printf("\n%d\t%d",i,d[i]);46 printf("\nNumber of comparisons:%d",count);47 printf("\nTime taken:%f seconds",time_taken);48 printf("\nTime complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix");49 printf("\nSpace complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix");50 printf("\n");51 return 0;52}6 ⏎ 0 1 1 0 0 0 ⏎ 1 0 0 1 1 0 ⏎ 1 0 0 0 1 0 ⏎ 0 1 0 0 0 1 ⏎ 0 1 1 0 0 1 ⏎ 0 0 0 1 1 0 ⏎ 1Enter the number of vertices:6 Enter the 6x6 adjacency matrix: 0 1 1 0 0 0 1 0 0 1 1 0 1 0 0 0 1 0 0 1 0 0 0 1 0 1 1 0 0 1 0 0 0 1 1 0 Enter the source vertex:1 BFS traversal: 1 2 3 4 5 6 Vertex Distance from 1 1 0 2 1 3 1 4 2 5 2 6 3 Number of comparisons:36 Time taken:0.000003 seconds Time complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix Space complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix
Run program 20 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.