我正在尝试为有向图编写一种方法DFS方法。现在我遇到了分割错误,我真的不确定它在哪里。根据我对有向图的了解,我相信我的逻辑是正确的......但是一组新的眼睛将会是一个很好的帮助。C++有向图深度优先搜索
这里是我的功能:
void wdigraph::depth_first (int v) const {
static int fVertex = -1;
static bool* visited = NULL;
if(fVertex == -1) {
fVertex = v;
visited = new bool[size];
for(int x = 0; x < size; x++) {
visited[x] = false;
}
}
cout << label[v];
visited[v] = true;
for (int v = 0; v < adj_matrix.size(); v++) {
for(int x = 0; x < adj_matrix.size(); x++) {
if(adj_matrix[v][x] != 0 && visited[x] != false) {
cout << " -> ";
depth_first(x);
}
if (v == fVertex) {
fVertex = -1;
delete [] visited;
visited = NULL;
}
}
}
}
类定义:
class wdigraph {
public:
wdigraph(int =NO_NODES); // default constructor
~wdigraph() {}; // destructor
int get_size() { return size; } // returns size of digraph
void depth_first(int) const;// traverses graph using depth-first search
void print_graph() const; // prints adjacency matrix of digraph
private:
int size; // size of digraph
vector<char> label; // node labels
vector< vector<int> > adj_matrix; // adjacency matrix
};
的感谢!
很好的答案。 (Paddity垫) – 2010-12-05 01:16:12