栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【数据结构基础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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/648745.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号