用链表表示图的 C++ 程序
图的关联矩阵是图的另一种表示形式,用于将其存储到内存中。此矩阵不是一个方阵。关联矩阵的阶数是 V x E。其中 V 是顶点数,E 是图中的边数。
在此矩阵的每一行中,我们放置顶点,而在每列中放置边。在此表示形式中,对于边 e {u, v},将在列 e 中用 1 来标记 u 和 v 位置。
邻接矩阵表示的复杂性
计算关联矩阵表示需要 O(V x E) 量级空间。对于完全图,边数将是 V(V-1)/2。因此,关联矩阵在内存中占用的空间较大。
输入

输出

算法
add_edge(adj_list, u, v)
输入 − 边 {u,v} 的 u 和 v 以及邻接表
输出 − 图 G 的邻接表
Begin Append v into the list at index u Append u into the list at index v End
示例代码
#include<iostream>
#include<list>
#include<iterator>
using namespace std;
void displayAdjList(list<int> adj_list[], int v) {
for(int i = 0; i<v; i++) {
cout << i << "--->";
list<int> :: iterator it;
for(it = adj_list[i].begin(); it != adj_list[i].end(); ++it) {
cout << *it << " ";
}
cout << endl;
}
}
void add_edge(list<int> adj_list[], int u, int v) { //add v into the list u, and u into list v
adj_list[u].push_back(v);
adj_list[v].push_back(u);
}
main(int argc, char* argv[]) {
int v = 6; //there are 6 vertices in the graph
//create an array of lists whose size is 6
list<int> adj_list[v];
add_edge(adj_list, 0, 4);
add_edge(adj_list, 0, 3);
add_edge(adj_list, 1, 2);
add_edge(adj_list, 1, 4);
add_edge(adj_list, 1, 5);
add_edge(adj_list, 2, 3);
add_edge(adj_list, 2, 5);
add_edge(adj_list, 5, 3);
add_edge(adj_list, 5, 4);
displayAdjList(adj_list, v);
}输出
0--->4 3 1--->2 4 5 2--->1 3 5 3--->0 2 5 4--->0 1 5 5--->1 2 3 4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP