如果在递归堆栈中找到顶点,则在有向图中检测到周期 - 为什么?

时间:2016-06-22 14:56:26

标签: algorithm recursion graph

我已阅读here中有关如何在有向图中检测周期的文章。这个算法的基本概念是如果在递归堆栈中找到一个节点然后有一个循环,但我不明白为什么。这里的逻辑是什么?

#include<iostream>
#include <list>
#include <limits.h>

using namespace std;

class Graph
{
    int V;    // No. of vertices
    list<int> *adj;    // Pointer to an array containing adjacency lists
    bool isCyclicUtil(int v, bool visited[], bool *rs);
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 in this graph
};

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.
}


bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack)
{
if(visited[v] == false)
{
    // Mark the current node as visited and part of recursion stack
    visited[v] = true;
    recStack[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 ( !visited[*i] && isCyclicUtil(*i, visited, recStack) )
            return true;
        else if (recStack[*i])
            return true;
    }

}
recStack[v] = false;  // remove the vertex from recursion stack
return false;
}


bool Graph::isCyclic()
{
// Mark all the vertices as not visited and not part of recursion
// stack
bool *visited = new bool[V];
bool *recStack = new bool[V];
for(int i = 0; i < V; i++)
{
    visited[i] = false;
    recStack[i] = false;
}


for(int i = 0; i < V; i++)
    if (isCyclicUtil(i, visited, recStack))
        return true;

return false;
}

int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

if(g.isCyclic())
    cout << "Graph contains cycle";
else
    cout << "Graph doesn't contain cycle";
return 0;
}

2 个答案:

答案 0 :(得分:2)

简单来说,代码片段是depth-first search的一种实现,它是有向图的基本搜索技术;同样的方法适用于breadth-first search。请注意,显然此实现仅在只有一个连接组件时才有效,否则必须对每个连接的组件执行测试,直到找到一个循环。

话虽这么说,该技术的工作原理是随意选择一个节点并在那里开始递归搜索。基本上,如果搜索发现堆栈中的节点,则必须有一个循环,因为之前已经达到过。

在当前实现中,recStack实际上不是堆栈,它只是指示特定节点当前是 in 堆栈,没有序列信息是存储。实际周期隐含在调用堆栈中。循环是尚未返回isCyclicUtil的调用的节点序列。如果必须提取实际周期,则必须更改实现。

答案 1 :(得分:0)

所以,这就是说,如果一个节点通向自身,那么就有一个循环。如果你考虑一下,这是有道理的!

假设我们从node1开始。

{node1 -> node2}
{node2 -> node3}
{node3 -> node4
 node3 -> node1}

{node4 -> end}
{node1 -> node2}
{node2 -> node3}.....

这是一个包含循环的小图。如您所见,我们遍历图表,从每个节点到下一个节点。在某些情况下,我们会到达并结束,但即使我们到达终点,我们的代码也希望返回到node3之外的其他分支,以便它可以检查它的下一个节点。然后,此节点返回node1

如果我们允许,这将永远发生,因为从node1开始的路径会回到自身。我们递归地将我们访问的每个节点放在堆栈上,如果我们到达终点,我们将从分支后的堆栈中删除所有节点。在我们的例子中,每次结束时我们都会从堆栈中删除node4,但由于node3的分支,其余的节点将保留在堆栈中。

希望这有帮助!