直接上代码:代码里面有注释
#pragma once
#include <assert.h>
#include <queue>
#include "Heap.hpp"
#include "UnionFindSet.hpp"
//
// 临接矩阵表示无向图&有向图
//
template<class V, class W>
class GraphMatrix
{
public:
GraphMatrix(const V* vertexs, int size, bool isDirected)
:_vertexSize(size)
,_isDirected(isDirected)
{
// 开辟矩阵和边集
_matrix = new W*[_vertexSize];
_vertexs = new V[_vertexSize];
for (int i = 0; i < _vertexSize; ++i)
{
// 初始化矩阵
_matrix[i] = new W[_vertexSize];
memset(_matrix[i], 0, sizeof(W)*_vertexSize);
// 初始化边集
_vertexs[i] = vertexs[i];
}
}
int GetVertexIndex(const V& vtx)
{
for (int i = 0; i < _vertexSize; ++i)
{
if (_vertexs[i] == vtx)
{
return i;
}
}
return -1;
}
void AddEdge(const V& src, const V& dst, const W& weight)
{
int srcIndex = GetVertexIndex(src);
int dstIndex = GetVertexIndex(dst);
assert(srcIndex != -1);
assert(dstIndex != -1);
if (_isDirected)
{
_matrix[srcIndex][dstIndex] = weight;
}
else
{
_matrix[srcIndex][dstIndex] = weight;
_matrix[dstIndex][srcIndex] = weight;
}
}
void Display()
{
for (int i = 0; i < _vertexSize; ++i)
{
cout<<_vertexs[i]<<" ";
}
cout<<endl<<endl;
for (int i = 0; i < _vertexSize; ++i)
{
for (int j = 0; j < _vertexSize; ++j)
{
cout<<_matrix[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
private:
W** _matrix; // 临接矩阵
V* _vertexs; // 顶点集
int _vertexSize; // 顶点数
//int _edgeSize; // 边条数
bool _isDirected;
};
// 无向图
void Test1()
{
GraphMatrix<char, int> g("ABCDE", 5, false);
g.AddEdge('A', 'D', 10);
g.AddEdge('A', 'E', 20);
g.AddEdge('B', 'C', 10);
g.AddEdge('B', 'D', 20);
g.AddEdge('B', 'E', 30);
g.AddEdge('C', 'E', 40);
g.Display();
}
// 有向图
void Test2()
{
GraphMatrix<char, int> g("ABCDE", 5, true);
g.AddEdge('A', 'D', 10);
g.AddEdge('E', 'A', 20);
g.AddEdge('B', 'C', 10);
g.AddEdge('D', 'B', 20);
g.AddEdge('E', 'B', 30);
g.AddEdge('C', 'E', 40);
g.Display();
}
//
// 临接表
//
template<class V, class W>
struct LinkEdge
{
int _srcIndex; // 源顶点下标
int _dstIndex; // 目标顶点下标
W _weight; // 权重
LinkEdge<V, W>* _next; // 指向下一个节点的指针
LinkEdge(int srcIndex = -1, int dstIndex = -1, const W& weight = W())
:_srcIndex(srcIndex)
,_dstIndex(dstIndex)
,_weight(weight)
,_next(NULL)
{}
};
template<class V, class W>
struct CompareLinkEdge