单独写一个路径的类,传入图和顶点,记录路径
代码
#pragma once
#include <vector>
#include <cassert>
#include <iostream>
#include <stack>
using namespace std;
template<typename Graph>
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<int>& vec) {
assert(hasPath(w));
stack<int> 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<int> 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<DenseGraph> readDenseGraph(DG, filename1);
DG.show();
cout << endl;
component<DenseGraph> DGcom(DG);
cout << "testG1 无向图的连通分量个数:" << DGcom.count() << endl;
cout << endl;
Path<DenseGraph> ph(DG, 0);
//查看0-4的路径
ph.showPath(4);
system("pause");
return 0;
}