0

C program to detect cycle in undirected graph

there is problem in my DFS_cycle function.

void cycle(struct Graph *graph)
{
    int t=0;
    for(int i=0;i<graph->V;i++)
    {
        if(graph->array[i].head!=NULL)
        {
            t=DFS_cycle(graph,i,-1);
            printf("i=%d t=%d",i,t);
        }
        if(t==1)
        {
            printf("Graph has cycle%d.",i);
            break;
        }
    }
    if(t==0)
    {
        printf("Graph has no cycle");
    }
}

I think something is missing in my DFS_cycle function. So my code terminates before calling DFS_cycle function.

int DFS_cycle(struct Graph *graph,int vi,int vj)
{
    struct adjListNode *p;
    p=graph->array[vi].head;
    if(graph->visited[vi]==1)  //if vertex already is visited and neighbour is not parrent.
    {
        if(p->dest!=vj)
            return(1);
    }
    else  //if not visited
    {
        while(p!=NULL)
        {
            if(DFS_cycle(graph,p->dest,vi))
                return(1);
            p=p->next;
        }
    }
    return(0);
}
kiner_shah
  • 3,939
  • 7
  • 23
  • 37
  • Edit the question to provide a [mre]. – Eric Postpischil Sep 11 '21 at 08:18
  • What is the definition of `struct Graph`? What is `vi` and `vj`? What is `struct adjListNode `? – kiner_shah Sep 11 '21 at 09:09
  • struct Graph is a structure containing V(number of vertex) vertex. vi and vj are vertex and struct adjListNode is a node which stores one element and address of next element. – Atulkumar Singh Sep 11 '21 at 09:49
  • What is the function `DFS_cycle` supposed to do with `graph`, `vi` and `vj`? It would be helpful if you can edit the question and add all the necessary description of the functions and their respective arguments. – kiner_shah Sep 11 '21 at 10:53

0 Answers0