繁体   English   中英

使用 BFS 找到一个循环并将其顶点保存在一个无向、未加权的图中

[英]Finding a cycle and saving its vertices in an undirected, unweighted graph using BFS

我一直试图让这个程序保存在图中形成循环的顶点。 但我是算法的新手,在使用 BFS 时实现该功能似乎有点复杂。 下面的代码成功找到了循环,但问题是如何修改此代码以便我可以打印构成循环的所有顶点?

#include <bits/stdc++.h>
using namespace std;
 
void addEdge(vector<int> adj[], int u, int v)
{
    adj[u].push_back(v);
    adj[v].push_back(u);
}
 
bool isCyclicConntected(vector<int> adj[], int s,
                        int V, vector<bool>& visited)
{
    // Set parent vertex for every vertex as -1.
    vector<int> parent(V, -1);
 
    // Create a queue for BFS
    queue<int> q;
 
    // Mark the current node as
    // visited and enqueue it
    visited[s] = true;
    q.push(s);
 
    while (!q.empty()) {
 
        // Dequeue a vertex from queue and print it
        int u = q.front();
        q.pop();
 
        // Get all adjacent vertices of the dequeued
        // vertex u. If a adjacent has not been visited,
        // then mark it visited and enqueue it. We also
        // mark parent so that parent is not considered
        // for cycle.
        for (auto v : adj[u]) {
            if (!visited[v]) {
                visited[v] = true;
                q.push(v);
                parent[v] = u;
            }
            else if (parent[u] != v)
                return true;
        }
    }
    return false;
}
 
bool isCyclicDisconntected(vector<int> adj[], int V)
{
    // Mark all the vertices as not visited
    vector<bool> visited(V, false);
 
    for (int i = 0; i < V; i++)
        if (!visited[i] && isCyclicConntected(adj, i,
                                         V, visited))
            return true;
    return false;
}
 
// Driver program to test methods of graph class
int main()
{
    int V = 4;
    vector<int> adj[V];
    addEdge(adj, 0, 1);
    addEdge(adj, 1, 2);
    addEdge(adj, 2, 0);
    addEdge(adj, 2, 3);
 
    if (isCyclicDisconntected(adj, V))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}

您可以使用parent链接来重建循环。

当两条 BFS 路径相遇时,这两条路径都可以通过串联parent链路重建,直到遇到一个公共节点。 这两条路径的长度可以相等(循环为偶数),也可以相差 1(循环为奇数)。 如果您以正确的方式通过相互的parent链接进行串联行走,您将始终遇到循环的“顶部”。

当您使用双端队列时,循环的节点将按自然顺序列出:来自第一条路径的节点可以推到前面,而另一条路径的节点则推到后面。

您实际上并不需要单独的visited向量:您也可以为此目的使用parent 没错,您启动 BFS 的第一个节点将不会被标记为已访问,但无法将其作为循环的终点进行访问,因为 BFS 将通过该源节点的所有边,并且不会允许使用任何这些边来访问源节点。 因此,为此目的使用parent就足够了。

这是您根据这些想法改编的代码:

void addEdge(vector<int> adj[], int u, int v)
{
    adj[u].push_back(v);
    adj[v].push_back(u);
}
 
bool isCyclicConnectedHelper(vector<int> adj[], int s,
                            int V, vector<int>& parent,
                            deque<int> &cycle)
{
    queue<int> q;
 
    q.push(s);
 
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (auto v : adj[u]) {
            if (parent[v] == -1) { // Not yet visited
                parent[v] = u;
                q.push(v);
            }
            else if (parent[u] != v) { // Not the same edge
                // Two paths meet: unwind both of them at both sides of a deque:
                while (u != v) {
                    cycle.push_front(v);
                    v = parent[v];
                    if (u == v) break;
                    cycle.push_back(u);
                    u = parent[u];
                }
                cycle.push_front(u);
                return true;
            }
        }
    }
    return false;
}
 
bool isCyclicConnected(vector<int> adj[], int V, deque<int> &cycle)
{
    vector<int> parent(V, -1);

    for (int i = 0; i < V; i++) {
        if (parent[i] == -1) {
            if (isCyclicConnectedHelper(adj, i, V, parent, cycle)) {
                return true;
            }
        }
    }
    return false;
}
 
// Driver program to test methods of graph class
int main()
{
    int V = 5;
    vector<int> adj[V];
    addEdge(adj, 0, 1);
    addEdge(adj, 1, 2);
    addEdge(adj, 2, 4);
    addEdge(adj, 3, 4);
    addEdge(adj, 4, 1);
 
    deque<int> cycle;
    if (isCyclicConnected(adj, V, cycle)) {
        cout << "The graph has a cycle:";
        for (auto v : cycle) {
            cout << " " << v;
        }
    } else {
        cout << "The graph has no cycle.";
    }
    cout << "\n";
    return 0;
}

注意:我建议将adj定义为vector<vector<int>>并调整addEdge以便根据需要扩展该向量。 这样你也可以摆脱V

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM