here is only basic implementation of problems for beginners. If you have any problem with any solution or any basic concept of programming or you want more efficient solution you can mail me.
my suggestion is not to copy and paste codes from here try to understand the logic and think why you were not able to solve it.

Saturday, 13 September 2014

dfs traversal of a graph using adjacency matrix

// complexity O(V+E)

#include<stdio.h>
int ar[100][100];
void dfs(int visited[],int i,int n){
int j;
visited[i]=1;
printf("%d\n",i);
for(j=0;j<n;j++){
if(ar[i][j]==1 && visited[j]!=1){
dfs(visited,j,n);
}
}
}
int main(){
int a,b,i,j,n,visited[101];
printf("Enter no of vertices\n");
scanf("%d",&n);
printf("Enter adjacency matrix\n");
for(i=0;i<n;i++){
visited[i]=0;
for(j=0;j<n;j++){
scanf("%d",&ar[i][j]);
}
}
for(i=0;i<n;i++){
if(visited[i]==0){
dfs(visited,i,n);
}
}
return 0;
}

No comments:

Post a Comment