在有向图中循环

时间:2015-02-07 08:59:35

标签: c graph directed-graph

我试图找出有向图中是否存在循环。 它的方法是什么? 算法也有帮助..

我使用邻接列表实现了图形,到目前为止一切正常

代码

#include<stdio.h>
#include<stdlib.h>
typedef struct Graph
{
    int vertex;
    struct Graph *next;
}Graph;
Graph *g[10];
void initializeGraph(int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        g[i]=(Graph*)malloc(sizeof(Graph));
        g[i]->vertex=i;
        g[i]->next=NULL;
    }
}
void addEdge(int v,int u)
{

    Graph *head=g[v];
    while(head->next)
        head=head->next;
    head->next=(Graph*)malloc(sizeof(Graph));
    head=head->next;
    head->next=NULL;
    head->vertex=u;

}
void printGraph(int n)
{
    Graph *head;
    int i;
    for(i=0;i<n;i++)
    {
        head=g[i];
        printf("\n");
        while(head)
        {
            if(head->next)
                printf("%d --->  ",head->vertex);
            else
                printf("%d ",head->vertex);
            head=head->next;
        }
    }

}
void checkCycle(int v,int n)
{
}
int main()
{
    int n,e,i,a[100],v,u;
    printf("\nEnter the number of vertices - ");
    scanf("%d",&n);

    initializeGraph(n);
    printf("\nEnter the number of edges - ");
    scanf("%d",&e);

    printf("\nVertices are - ");
    for(i=0;i<n;i++)
        printf("%d ",i);


    printf("\nEnter the edges separated by space - ");
    for(i=0;i<e;i++)
    {
        scanf("%d%d",&v,&u);
        addEdge(v,u);
    }
    printGraph(n);
    checkCycle(0,n);
    printf("\n\n");
}

如果任何人都可以完成这项功能,那真的很有帮助! 感谢

** EDIT1:** 我试过这个

//Global arrays - visited[],isCycle[]
//visited[] is initialized to 0
//isCycle[] initialized to -1    

//Method call : checkCycle(0,n);

int checkCycle(int v,int n)
{
    Graph *head;
    int w;
    visited[v]=1;
    head=g[v]->next;
    while(head)
    {
        w=head->vertex;
        if(visited[w])
            return 1;

        if(isCycle[w]==-1)
            checkCycle(w,n);        //We haven't visited that vertex yet
        else
            return 0;           //We visited this vertex before but a cycle was not found
        head=head->next;
    }
    visited[v]=0;
    isCycle[v]=0;
    return 0;

}


**Sample Input 1** - 
Enter the number of vertices - 4

Enter the number of edges - 4

Vertices are - 0 1 2 3 
Enter the edges separated by space - 0 1 
1 2
2 3
3 0

0 --->  1 
1 --->  2 
2 --->  3 
3 --->  0 


Cycle Does not exist


**Sample Input 2**- 
Enter the number of vertices - 4

Enter the number of edges - 3

Vertices are - 0 1 2 3 
Enter the edges separated by space - 0 1
1 2
2 3

0 --->  1 
1 --->  2 
2 --->  3 
3 


Cycle Does not exist

注意:在每个案例输出中 - 周期不存在。

1 个答案:

答案 0 :(得分:1)

编辑1部分中的

:你总是得到&#34;周期不存在&#34;因为你发现它时没有回复正确的答案。

程序中唯一的错误是

的状态检查
if(isCycle[w] == -1) 
      return checkCycle(w, n);

在此之前你没有返回正确的答案,所以默认你发送了错误的答案,即返回false。 :)

快乐编码!!!