我正在为有向图实现一个简单的 DFS 遍历:
#include <iostream>
#include <vector>
#include <climits>
#include <utility>
#include <deque>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <list>
using namespace std;
enum class color_type {
BLACK,
WHITE,
GRAY
};
struct vertex {
char label;
color_type color;
int start;
int finish;
vertex *parent;
vector<vertex> adjacents;
vertex(char label)
:label(label), start(0), finish(0), color(color_type::WHITE) {
}
void add_neighbor(const vertex &v) {
adjacents.push_back(v);
}
};
class digraph {
private:
vector<vertex> vertices;
int count;
public:
digraph()
:count(0) {
vertex a('a');
vertex b('b');
vertex c('c');
add_edge(a, b);
add_edge(b, c);
add_edge(c, a);
vertices.push_back(a);
vertices.push_back(b);
vertices.push_back(c);
for (int i = 0; i < vertices.size(); ++i) {
vertices[i].color = color_type::WHITE;
vertices[i].parent = NULL;
}
}
void add_edge(vertex &u, vertex &v) {
u.add_neighbor(v);
}
void dfs() {
dfs_visit(vertices[0]);
}
void dfs_visit(vertex &u) {
count++;
u.start = count;
u.color = color_type::GRAY;
cout << "??? visit = " << u.label << endl;
cout << "# neighbors: " << u.adjacents.size() << '\n';
for (int i = 0; i < u.adjacents.size(); ++i) {
if (u.adjacents[i].color == color_type::WHITE) {
cout << "visit neighbor of [" << u.label << "] is: " << u.adjacents[i].label << endl;
u.adjacents[i].parent = &u;
dfs_visit(u.adjacents[i]);
}
}
u.color = color_type::BLACK;
count++;
u.finish = count;
}
public:
friend ostream& operator <<(ostream& o, const digraph &dg) {
for (int i = 0; i < dg.vertices.size(); ++i) {
o << dg.vertices[i].label << ":\n";
o << "\t start = " << dg.vertices[i].start << endl;
o << "\t finish = " << dg.vertices[i].finish << endl;
}
return o;
}
};
int main() {
digraph dg;
dg.dfs();
cout << dg << endl;
return 0;
}
问题是dfs_visit()
访问第二个顶点后停止调用。我通过引用传递一个顶点u
作为dfs_visit()
函数的参数,但不知何故,顶点的邻居数b
突然变得0
非常奇怪。
在我看来,存储在向量vertices
中的顶点与传递给的顶点不同dfs_visit
,但我真的不明白这是怎么回事。我使用 Java 已经有一段时间了,现在我对 C++ 真的很生疏了。那么有人可以就这个问题向我解释一下吗?
编辑