Tuesday 18 November 2014

Depth First Search in a Graph

Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking



C Code:
#include<stdio.h>
DFS(int cur,int n,int visit[],int adj[][n])
{
    printf("%d\n",cur+1);
    visit[cur]=1;
    int i;
    for(i=0;i<n;i++)
    {
        if(adj[cur][i]&&!(visit[i]))
        {
            DFS(i,n,visit,adj);
        }
    }
}
main()
{
int n;
printf("Enter the total number of nodes\n");
scanf("%d",&n);
int adj[n][n];
int i,j;
for(i=0;i<n;i++)
{
    for(j=0;j<n;j++)
    {
        printf("Is node %d connected to node %d",i+1,j+1);//Press 1 if yes else press 0
        scanf("%d",&adj[i][j]);
    }
}
printf("Enter the starting node\n");
int start;
scanf("%d",&start);
start--;
int visit[n];
for(i=0;i<n;i++)
{
    visit[i]=0;
}
DFS(start,n,visit,adj);
}

No comments:

Post a Comment