Finding all cycles in a directed graph

前端 未结 17 2206
渐次进展
渐次进展 2020-11-22 05:47

How can I find (iterate over) ALL the cycles in a directed graph from/to a given node?

For example, I want something like this:

A->B->A
A->B         


        
17条回答
  •  情话喂你
    2020-11-22 06:15

    Regarding your question about the Permutation Cycle, read more here: https://www.codechef.com/problems/PCYCLE

    You can try this code (enter the size and the digits number):

    # include
    using namespace std;
    
    int main()
    {
        int n;
        scanf("%d",&n);
    
        int num[1000];
        int visited[1000]={0};
        int vindex[2000];
        for(int i=1;i<=n;i++)
            scanf("%d",&num[i]);
    
        int t_visited=0;
        int cycles=0;
        int start=0, index;
    
        while(t_visited < n)
        {
            for(int i=1;i<=n;i++)
            {
                if(visited[i]==0)
                {
                    vindex[start]=i;
                    visited[i]=1;
                    t_visited++;
                    index=start;
                    break;
                }
            }
            while(true)
            {
                index++;
                vindex[index]=num[vindex[index-1]];
    
                if(vindex[index]==vindex[start])
                    break;
                visited[vindex[index]]=1;
                t_visited++;
            }
            vindex[++index]=0;
            start=index+1;
            cycles++;
        }
    
        printf("%d\n",cycles,vindex[0]);
    
        for(int i=0;i<(n+2*cycles);i++)
        {
            if(vindex[i]==0)
                printf("\n");
            else
                printf("%d ",vindex[i]);
        }
    }
    

提交回复
热议问题