#pragma once #include测试#include #include #include using namespace std; template class Path { private: Graph& G; bool* visited; int s; //source int* from; void dfs(int v) { //深度优先遍历 visited[v] = true; typename Graph::adjIterator adj(G, v); for (int it = adj.begin(); !adj.end();it = adj.next()) { if (!visited[it]) { from[it] = v; dfs(it); } } } public: Path(Graph& graph, int s) :G(graph) { assert(s >= 0 && s < G.V()); this->s = s; visited = new bool[G.V()]; from = new int[G.V()]; for (int i = 0; i < G.V(); ++i) { visited[i] = false; from[i] = -1; } dfs(s); } ~Path() { delete[] visited; delete[] from; } //s 和 w之间是否有路径 bool hasPath(int w) { assert(w >= 0 && w < G.V()); return visited[w]; } void path(int w, vector & vec) { assert(hasPath(w)); stack stk; vec.clear(); int p = w; while (p != -1) { stk.push(p); p = from[p]; } while (!stk.empty()) { vec.push_back(stk.top()); stk.pop(); } } void showPath(int w) { assert(hasPath(w)); vector vec; path(w, vec); for (int i = 0; i < vec.size(); ++i) { cout << vec[i]; if (i != vec.size() - 1) cout << "->"; else cout << endl; } } };
int main() {
string filename1 = "testG1.txt";
DenseGraph DG(13, false);
readGraph readDenseGraph(DG, filename1);
DG.show();
cout << endl;
component DGcom(DG);
cout << "testG1 无向图的连通分量个数:" << DGcom.count() << endl;
cout << endl;
Path ph(DG, 0);
//查看0-4的路径
ph.showPath(4);
system("pause");
return 0;
}



