[英]Detect cycle in an undirected graph
為了檢測無向圖中的循環,給出了以下代碼anf算法; 我正在使用正常的廣度優先遍歷以及輕微的修改:
void bfsUtil(int s,vector<bool> &visited,vector<int> adj[],vector<int> &visits) {
queue<int> q;
q.push(s);
visits[s]++;
visited[s]=true;
while(!q.empty()) {
int vertex=q.front();
q.pop();
for(int i=0;i<adj[vertex].size();i++) {
if(!visited[adj[vertex][i]]) {
visited[adj[vertex][i]]=true;
q.push(adj[vertex][i]);
visits[adj[vertex][i]]++;
} else {
visits[adj[vertex][i]]++;
}
}
}
}
/* This function is used to detect a cycle in undirected graph
* adj[]: array of vectors to represent graph
* V: number of vertices
*/
bool isCyclic(vector<int> adj[], int V)
{
vector<int> visits(V,0);
vector<bool> visited(V,false);
for(int i=0;i<V;i++){
if(!visited[i]) {
bfsUtil(i,visited,adj,visits);
}
}
for(int i=0;i<visits.size();i++) {
if(visits[i]>2) {
return true;
}
}
return false;
}
Algorithm:
1. Normal Breadth first search and maintaining a count aray for the no of visits of each vertex.
2. If no of visits>2
print cycle is present
else
print no cycle
但是對於以下測試用例,我的回答是錯誤的:
Input:
46 45
0 44 1 23 1 35 1 37 1 38 2 20 2 35 3 13 4 44 5 21 5 36 6 41 7 8 8 18 9 17 9 41 9 45 10 13 10 21 10 33 10 34 10 39 10 42 11 17 12 24 13 44 14 19 15 25 16 34 18 24 19 25 21 24 21 26 22 37 23 28 25 31 25 35 25 40 25 41 25 44 27 43 27 44 29 40 30 34 32 33
Its Correct output is:
0
And Your Code's output is:
1
我的算法哪里出錯了?
你的算法是錯誤的。 考慮以下邊的圖:
0 - 1
0 - 2
當當前節點為 1 時,它也檢查 0,因為從 1 到 0 也有一條邊。 所以它將增加訪問計數 0。同樣,2 也會增加計數。 所以你的代碼總是會錯誤地檢測周期。
要解決此問題,您應該為每個節點保留一個父節點,從該節點訪問該節點。 當你檢查時,你永遠不應該考慮父母的優勢。 最后,您不需要訪問數組。 如果發現相鄰節點不是當前節點的父節點,但之前仍然訪問過,則可以斷定存在循環。
修改您的代碼:
bool bfsUtil(int s,vector<bool> &visited,vector<int> adj[],vector<int> &parent) {
queue<int> q;
q.push(s);
visited[s]=true;
while(!q.empty()) {
int vertex=q.front();
q.pop();
for(int i=0;i<adj[vertex].size();i++) {
if(adj[vertex][i] == parent[vertex])
continue;
if(!visited[adj[vertex][i]]) {
visited[adj[vertex][i]]=true;
q.push(adj[vertex][i]);
parent[adj[vertex][i]] = vertex;
} else {
//cycle detected;
return true;
}
}
}
return false;
}
/* This function is used to detect a cycle in undirected graph
* adj[]: array of vectors to represent graph
* V: number of vertices
*/
bool isCyclic(vector<int> adj[], int V)
{
vector<bool> visited(V,false);
vector<int> parent(V, -1); // -1 means no parent assigned
for(int i=0;i<V;i++){
if(!visited[i]) {
if(bfsUtil(i,visited,adj,parent)) return true;
}
}
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.