图集的表示方法主要有以下几种:
邻接矩阵法
好处:方便找任一顶点的所有邻接点,节约稀疏图的空间。
坏处:对于检查任意一对顶点间是否存在边并不方便。
代码示例:
邻接链表法
好处:对于检查任意一对顶点间是否存在边方便,适合稀疏图。
坏处:需要更多的存储空间来存储边的信息。
代码示例:
include
include
using namespace std;
typedef int Vertex;
typedef struct Edge {
Vertex dest;
WeightType weight;
Edge* next;
} Edge;
typedef struct Graph {
Vertex numOfVertices;
Edge adjList;
} Graph;
Graph* createGraph(Vertex numOfVertices) {
Graph* graph = new Graph();
graph->numOfVertices = numOfVertices;
graph->adjList = new Edge*[numOfVertices];
for (Vertex i = 0; i < numOfVertices; i++) {
graph->adjList[i] = nullptr;
}
return graph;
}
void addEdge(Graph* graph, Vertex src, Vertex dest, WeightType weight) {
Edge* newEdge = new Edge();
newEdge->dest = dest;
newEdge->weight = weight;
newEdge->next = graph->adjList[src];
graph->adjList[src] = newEdge;
}
void printGraph(Graph* graph) {
for (Vertex i = 0; i numOfVertices; i++) {
Edge* edge = graph->adjList[i];
cout << "Vertex "<< i < ";
while (edge != nullptr) {
cout << "(" <dest << ", " <weight << ") ";
edge = edge->next;
}
cout << endl;
}
}
int main() {
Graph* graph = createGraph(3);
addEdge(graph, 0, 1, 1);
addEdge(graph, 0, 2, 1);
addEdge(graph, 1, 2, 1);
printGraph(graph);
return 0;
}
我们致力于保护作者版权,注重分享,被刊用文章【图集表示方法】因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(本人原创文章,百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!发布者:云建筑,转转请注明出处:https://www.yunjianzhu.com/4724.html