C++ 无权图的实现模板

测试主函数,包括从文件中读取图,以及DFS,和BFS算法实现

#include <iostream>
#include "SpareseGraph.h"
#include "DenseGraph.h"
#include "ReadGraph.h"
#include "Component.h"
#include "Path.h"
#include "ShortestPath.h"
using namespace std;

int main()
{
	string filename1 = "testG1.txt";
	SpareseGraph g1(13, false);
	//DenseGraph g1(13, false);
	ReadGraph<SpareseGraph> readGraph1(g1, filename1);
	Component<SpareseGraph> component1(g1);
	cout << "TestG1.txt, Component Count: " << component1.count() << endl;

	string filename2 = "testG2.txt";
	SpareseGraph g2(7, false);
	//DenseGraph g1(7, false);
	ReadGraph<SpareseGraph> readGraph2(g2, filename2);
	Component<SpareseGraph> component2(g2);
	cout << "TestG1.txt, Component Count: " << component2.count() << endl;

	Path<SpareseGraph> dfs(g2, 0);
	cout << "DFS : ";
	dfs.showPath(6);

	ShortestPath<SpareseGraph> bfs(g2, 0);
	cout << "BFS : ";
	bfs.showPath(6);
	return 0;
}

稠密图(邻接矩阵的实现),这里巧妙的地方是将邻接矩阵设为私有成员变量,实现一个迭代器的类,这样的实现可以统一将稀疏图和稠密图的操作用一套代码实现

DenseGraph.h

#include <iostream>
#include <vector>
#include <cassert>

using namespace std;

class DenseGraph {
private:
	int n, m;                    // n为定点数,m为边数
	bool directed;               // 是否为有向图
	vector<vector<bool>> g;      // 邻接矩阵

public:
	DenseGraph(int n, bool directed) {
		this->n = n;
		this->m = m;
		this->directed = directed;
		for (int i = 0; i < n; i++) {
			g.push_back(vector<bool>(n, false));
		}
	}

	~DenseGraph(){

	}

	int V() {
		return n;             // 返回顶点数
	}

	int E() {
		return m;            //  返回边数
	}

	void addEdge(int v, int w) {
		assert(v >= 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值