我如何通过所有可能的节点进行迭代并确定它是否是欧拉电路?

时间:2017-04-20 20:22:50

标签: c++ graph

我似乎无法遍历所有节点。它只通过一个或两个节点,并且无论如何都无法返回true。我希望程序通过节点多次迭代以获得所有可能的结果,但仍然是欧拉电路。这只是一个小例子。要确定它是否是欧拉电路,它必须只通过一次边缘。每当我尝试递归函数DFSUtil时,它将停在第一个节点或第二个节点。 例如:

start = A
End = C
A connect to B
A connect to C
B connect to A
B connect to C
C connect to B

Result: 2 path
A -> B -> C -> B -> A -> C
A -> B -> A -> C -> B -> C



#include <iostream>
#include <string>
#include <string.h>
#include <sstream>
#include <stdio.h>
#include <stack>
#include <vector>


using namespace std;

unsigned int V;

class node
{
    public:
    string Enzyme;
    vector<node> connection;
    node(string Enzyme)
    {
        this->Enzyme = Enzyme;
    }

    bool isEulerCircuit();
    bool isConnected();
    string DFSUtil(unsigned int v,bool visited[]);
    void add_edge(node &n)
    {
        connection.push_back(n); 
        cout << Enzyme <<  "  connected to  " << n.Enzyme << endl;
    }

};

string node::DFSUtil(unsigned int v,bool visited[])
{
    visited[v] = true;
    vector<node>::iterator it;
    string res;
    for(it = connection.begin(); it != connection.end(); it++)
    {
        cout << (*it).Enzyme << endl;
        if(!visited[v])
        {
            res+= (*it).Enzyme;
            DFSUtil(v,visited);
        }

    }
    return res;
}

bool node::isEulerCircuit()
{
    if (isConnected() == false)
    {
        return false;
    }
    return true;
}

bool node::isConnected()
{
    bool visited[V];
    for(int i = 0; i < V; i++)
    {
        visited[i] = false;
    }

    int n=3;

    DFSUtil(n,visited);

    for (int i = 0; i < V; i++)
    {
        if (visited[i] == false)
        {
              return false;
        }
    }

    return true;
}

int main()
{
    vector<node> nod;
    string A = "A";
    string B = "B";
    string C = "C";

    nod.push_back(A);
    nod.push_back(B);
    nod.push_back(C);



    for(int i = 0; i < nod.size(); i++)
    {
        V = i;
    }

    cout << endl;

    nod[0].add_edge(nod[1]);
    nod[0].add_edge(nod[2]);
    nod[1].add_edge(nod[0]);
    nod[1].add_edge(nod[2]);
    nod[2].add_edge(nod[1]);



    if(nod[0].isEulerCircuit())
    {
        cout << "HI" << endl;
    }
    else
    {
        cout << "BYE" << endl;
    }



    return 0;
}

0 个答案:

没有答案