目录
一.邻接矩阵
1.1概念介绍
邻接矩阵(二维数组)即是:先用一 个数组将定点保存,然后采用矩阵来表示节点与节点之间的关系。矩阵可以存储0或者1来表示两个顶点之间是否连通,也可以存储权值。. 用邻接矩阵存储图是能够快速知道两个顶点是否连通,缺陷是如果顶点比较多,边比较少时,矩阵中存储了大量值为0的矩阵,比较浪费空间,并且要求两个节点之间的路径不是很好求。
例如:
上面的邻接矩阵中,如果两个顶点之间不连通的话,用无穷大来表示。上面的是有向图,无向图的矩阵是对称的。
1.2代码示例
我们需要存储各个顶点以及顶点之间边的信息。存储边的信息可以用一个二维数组来表示,这里会用到下标,所以可以用一个map来存储顶点与对应下标的映射关系。
template<class V,class W, W W_MAX=INT_MAX,bool Direc=false>// v表示边的类型,W表示权值类型,W_MAX默认为INT_MAX
class Grap
{
public:
Grap(const V* a,int n)
{
_vertexs.resize(n);
for (int i = 0; i < n; i++)
{
_vertexs[i] = a[i]; //顶底集合初始化
_indexMap[a[i]] = i; //映射初始化
}
_matrix.resize(n);
for (size_t i = 0; i < _matrix.size(); ++i) //矩阵初始化
{
_matrix[i].resize(n, 0);
}
}
int get_index(const V a)
{
auto it = _indexMap.find(a);
if (it != _indexMap.end())
{
return it->second;
}
else
{
exit(-1);
}
}
void _AddEdge(size_t srci, size_t dsti, const W& w)
{
_matrix[srci][dsti] = w;
if (Direc == false)// 无向图
{
_matrix[dsti][srci] = w;
}
}
void AddEdge(const V& src, const V& dst, const W& w)//添加两个顶点的边,附上权值
{
int srci = get_index(src);
int dsti = get_index(dst);
_AddEdge(srci, dsti, w);
}
void Print()
{
int n = _vertexs.size();
cout << " ";
for (int i = 0; i < n; i++)
{
printf("%-3c", _vertexs[i]);
}
cout << endl;
for (int i = 0; i < n; i++)
{
cout << _vertexs[i] << " ";
for (int j = 0; j < n; j++)
{
//cout << _matrix[i][j] << " ";
printf("%3d", _matrix[i][j]);
}
cout << endl;
}
}
private:
vector<V> _vertexs; // 顶点集合
map<V, int> _indexMap; // 顶点映射下标
vector<vector<W>> _matrix; // 邻接矩阵
};
1.3代码测试
int main()
{
char a[] = "ABCDE";
Grap<char, int> G(a,5);
G.AddEdge('A', 'B', 7);
G.AddEdge('A', 'D', 3);
G.AddEdge('C', 'D', 4);
G.AddEdge('C', 'E', 6);
G.Print();
return 0;
}
结果: