用于检测图中的循环的算法的修改

时间:2015-07-31 14:00:09

标签: c++ algorithm graph

在下面的代码中,我检查图表是否包含循环,它是100%工作,但我确实想要修改它而不是打印是,我希望它打印的第一个节点重复循环。因此,例如,如果实际图形有一个周期,周期是0,1,3,5,7,0,而不是是,我想打印0。 或者如果循环是1,3,5,7,8,1它应该打印1.如果有人有想法我会很感激,谢谢。

#include<iostream>
#include <list>
#include <limits.h>
using namespace std;

// Class for an undirected graph
class Graph
{
    int V;    // No. of vertices
    list<int> *adj;    // Pointer to an array containing adjacency lists
    bool isCyclicUtil(int v, bool visited[], int parent);
public:
    Graph(int V);   // Constructor
    void addEdge(int v, int w);   // to add an edge to graph
    bool isCyclic();   // returns true if there is a cycle
};

Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[V];
}

void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w); // Add w to v’s list.
    adj[w].push_back(v); // Add v to w’s list.
}

// A recursive function that uses visited[] and parent to detect
// cycle in subgraph reachable from vertex v.
bool Graph::isCyclicUtil(int v, bool visited[], int parent)
{
    // Mark the current node as visited
    visited[v] = true;

    // Recur for all the vertices adjacent to this vertex
    list<int>::iterator i;
    for (i = adj[v].begin(); i != adj[v].end(); ++i)
    {
        // If an adjacent is not visited, then recur for that adjacent
        if (!visited[*i])
        {
            if (isCyclicUtil(*i, visited, v))
                return true;
        }

        // If an adjacent is visited and not parent of current vertex,
        // then there is a cycle.
        else if (*i != parent)
            return true;

    }
    return false;
}

// Returns true if the graph contains a cycle, else false.
bool Graph::isCyclic()
{
    // Mark all the vertices as not visited and not part of recursion
    // stack
    bool *visited = new bool[V];
    for (int i = 0; i < V; i++)
        visited[i] = false;

    // Call the recursive helper function to detect cycle in different
    // DFS trees
    for (int u = 0; u < V; u++)
        if (!visited[u]) // Don't recur for u if it is already visited
            if (isCyclicUtil(u, visited, -1)){
                return true;
            }

    return false;
}

// Driver program to test above functions
int main()
{
    int res=0;
    int m, n;
    cin >> m >> n;

    Graph g1(m);
    for(int i=0; i<n; i++) {
        int q, r;
        cin >> q >> r;
        g1.addEdge(q, r);
    }

    g1.isCyclic()? cout << "Yes":
    cout << "No";

    return 0;
}

2 个答案:

答案 0 :(得分:0)

一旦找到一个循环,通过访问您已访问过的节点,您就知道该节点是循环的一部分。 然后,您可以只对节点本身进行深度优先搜索。找到后,输出堆栈中的所有节点。

如果你想要有效编码,你也可以找到这样的循环,然后输出所有节点,直到你到达你找到循环的节点。

答案 1 :(得分:0)

找到一个tological顺序(或者只是序列化搜索顺序)并使用hash来重复节点和已经看过的循环。打印搜索开始节点编号。根据您的搜索顺序,您的搜索结果可能会有所不同。