Thursday, December 1, 2011

Program for Depth First Search for an un-directed Graph using C

#include

#define MAX 10
int n;
int adj[MAX][MAX];
int visited[MAX];

void readmatrix()
{
    int i,j;
    printf("\nEnter the number of Vertices in the Graph : ");
    scanf("%d",&n);
    printf("\nEnter the Adjacency Matrix\n\n");
    for (i = 1; i <= n; i++)
        for (j = 1; j<= n; j++)
            scanf("%d",&adj[i][j]);
    for (i = 1; i <= n; i++)
        visited[i] = 0;
}


int dfs(int start)
{
    int stack[MAX];
    int top=-1,i;
    printf("%d - ",start);
    visited[start]=1;
    stack[++top]=start;
    while(top!=-1)
    {
      start=stack[top];
      for(i=1;i<=MAX;i++)
      {
         if(adj[start][i]&&visited[i]==0)
          {
             stack[++top]=i;
             printf("%d-",i);
             visited[i]=1;
             break;
           }
       }

     if(i==MAX)
             top--;
    }
    return 0;
}

int main()
{

    int source;
    printf("\n Program for Depth First Search for an un-directed Graph");
    readmatrix();
    printf("\nEnter the Source : ");
    scanf("%d",&source);
    printf("\nThe nodes visited in the DFS order is : ");
    dfs(source);
    printf("\n");
    return 0;
}

No comments:

Post a Comment