【数据结构基础C++】图论05-利用深度优先算法查询路径

【数据结构基础C++】图论05-利用深度优先算法查询路径,第1张

【数据结构基础C++】图论05-利用深度优先算法查询路径 单独写一个路径的类,传入图和顶点,记录路径


代码
#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;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5650940.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存