[英]Modification of an algorithm for detecting cycles in a graph
在下面的代碼中,我檢查圖形是否包含周期,並且它正在100%工作,但是我確實想對其進行修改,而不是打印Yes,而是希望它打印周期重復的第一個節點。 因此,例如,如果實際圖形有一個循環,並且循環是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;
}
找到周期后,通過訪問已訪問的節點,您知道該節點是周期的一部分。 然后,您可以先深度搜索節點本身。 找到它后,輸出堆棧上的所有節點。
如果您想提高編碼效率,也可以找到循環,然后輸出所有節點,直到到達找到循環的節點為止。
查找邏輯順序(或僅序列化搜索順序),然后使用哈希值重復節點和已經看到的循環。 打印搜索開始節點號。 根據您的搜索順序,結果可能會有所不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.