我可以将数据放在相邻列表图的边缘吗?
我的要求有这些行:
(A) 所需信息:
A-1. 100个城市,每个城市的游览时间
A2。 300 次带价格的站点间运输
(B) 显示直接访问的城市图表(100 个站点,其中有 300 条直接路径)
(C) 该图由具有一定距离的边组成
从(B)开始,我认为城市是顶点,路线(交通)是边。
(A. Needed information) 表示运输本身应该有价格
(C) 表示边缘有距离。
这就是为什么我对将数据放在边缘的方法感到好奇的原因。
我以为edge只是一个抽象的概念,实际上是通过将另一个节点的地址赋予该节点来实现的。
喜欢:
struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
如何用数据实现边缘?谢谢。
是的,您可以将数据与图形边相关联,这与您表示图形的方式无关。想想你会如何解决 shortest path problem ;您显然需要知道图中两个节点之间的距离,并且此信息是连接它们的边的属性,而不是单个节点。
在您的示例中,您可以:
// create reciprocal links between nodes 'src' and 'dst',
// containing the 'distance' information
void graph_link_two_cities(struct Graph* graph, int src, int dst, int distance)
{
{
struct Edge* head = graph->array[src].head;
struct Edge* node = { .id = dst, .distance = length, .next = head });
graph->edges[src].head = node;
}
{
struct Edge* head = graph->array[dst].head;
struct Edge* node = { .id = src, .distance = length, .next = head });
graph->edges[dst].head = node;
}
}
使用邻接矩阵,您只需存储 src
之间的距离和 dst
进入matrix[src][dst]
.