测试主函数,包括从文件中读取图,以及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 >=