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