我正在嘗試爲有向圖編寫一種方法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