我有这个代码,用于检查有向图中是否存在2个顶点(x和y)之间的路径(道路)。
#include<iostream>
#include <list>
using namespace std;
class Graf
{
private:
int Vf;
list<int> *adj;
public:
// Constructor
Graf(int Vf)
{
this->Vf = Vf;
adj = new list<int>[Vf];
}
void addEdge(int vf, int w) // add
{
adj[vf].push_back(w);
}
bool isGRoad(int first, int second)
{
if (first == second) // cazul in care
return true;
bool *visited = new bool[Vf];
for (int i = 0; i < Vf; i++)
visited[i] = false;
list<int> myQueue;
visited[first] = true;
myQueue.push_back(first);
list<int>::iterator index;
while (!myQueue.empty())
{
first = myQueue.front();
myQueue.pop_front();
for (index = adj[first].begin(); index != adj[first].end(); ++index)
{
if (*index == second)
return true;
if (!visited[*index])
{
visited[*index] = true;
myQueue.push_back(*index);
}
}
}
return false;
}
};
int main()
{
int nrVf;
cin >> nrVf;
Graf graf(nrVf);
int ok = -5;
for (int i = 1; i <= nrVf; ++i)
{
cout << i << ": ";
cin >> ok;
while (ok != -1)
{
graf.Graf::addEdge(i, ok);
cin >> ok;
}
ok = 0;
}
int x, y;
cin >> x >> y;
if (graf.isGRoad(x, y))
cout << "Exista drum de la " << x << " la " << y << ".\n";
else
cout << "Nu exista drum de la " << x << " la " << y << ".\n";
return 0;
}
现在我想更改我的代码以检查x和y之间是否存在链。路径(道路)和链条之间的区别在于链条上的方向并不重要。我无法弄清楚如何检查它是否是一个链而不仅仅是一条路径。有人能帮忙吗?