【问题标题】:What is odd length cycle and how can I know if there is an odd cycle in my graph?什么是奇数循环,我如何知道我的图表中是否存在奇数循环?
【发布时间】:2012-07-03 14:33:31
【问题描述】:

我是图论的新手。假设有一个连通无向图。我想知道它是否有一个奇数长度的循环。我可以使用 BFS 找到我的图表中是否存在循环。我还没学过DFS。这是我的代码,它只是查找是否存在循环。提前致谢。

#include<iostream>
#include<vector>
#include<queue>
#include<cstdio>
#define max 1000

using namespace std;

bool find_cycle(vector<int> adjacency_list[]);

int main(void)
{
     freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);

int vertex, edge;
vector<int> adjacency_list[max];

cin >> vertex >> edge;

//Creating the adjacency list
for(int i=1; i<=edge; i++)
{
    int n1, n2;
    cin >> n1 >> n2;

    adjacency_list[n1].push_back(n2);
    adjacency_list[n2].push_back(n1);
}

if(find_cycle(adjacency_list))
    cout << "There is a cycle in the graph" << endl;
else cout << "There is no cycle in the graph" << endl;

return 0;
}

bool find_cycle(vector<int> adjacency_list[])
{
queue<int> q;
bool taken[max]= {false};
int parent[max];

q.push(1);
taken[1]=true;
parent[1]=1;

//breadth first search
while(!q.empty())
{
    int u=q.front();
    q.pop();

    for(int i=0; i<adjacency_list[u].size(); i++)
    {
        int v=adjacency_list[u][i];

        if(!taken[v])
        {
            q.push(v);
            taken[v]=true;
            parent[v]=u;
        }
        else if(v!=parent[u]) return true;
    }
}

return false;
}

【问题讨论】:

  • 提示:一个图没有奇数循环当且仅当它是2-colorable
  • @AdamRosenfield,非常感谢。
  • @AdamRosenfield,我应该搜索整个图还是只搜索包含循环的子图。因为图中可以有不止一个循环。
  • 这对于你扔给它的每个图表是否都返回 true?
  • @Wug,对于无向图和连通图,它应该返回 true。但我还没有检查所有棘手的情况。

标签: c++ algorithm graph cycle breadth-first-search


【解决方案1】:

属性“2-colorable”也称为“二分”。在这种情况下,使用 DFS 还是 BFS 无关紧要。当您访问图形的节点时,根据您来自的邻居的颜色,将它们标记为 0 / 1。如果您发现一个节点已被标记,但标记与您在访问时标记的不同,则存在一个奇数长度的循环。如果没有出现这样的节点,则不存在奇数长度的循环。

【讨论】:

    猜你喜欢
    • 2018-06-05
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    相关资源
    最近更新 更多