Implementing Weighted edges to graph
我想能够实现一个最短路径算法,但我意识到没有重量的实际边缘本身。我想改变我的结构,这样我就可以用一个数值来表示从一个顶点到另一个顶点的权重。我将如何实现这一点?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | #include<stdio.h> #include<stdlib.h> struct edge { int vertexIndex; struct edge *edgePtr; }edge; struct vertex { int vertexKey; struct edge *edgePtr; }vertex; struct vertex graph[1000]; int vertexCount=0; void InsertVertex(int vertexKey) { graph[vertexCount].vertexKey=vertexKey; graph[vertexCount].edgePtr=NULL; vertexCount++; } void insertEdge(int vertex1, int vertex2) { struct edge *e,*e1,*e2; e=graph[vertex1].edgePtr; while(e&& e->edgePtr) { e=e->edgePtr; } e1=(struct edge *)malloc(sizeof(*e1)); e1->vertexIndex=vertex2; e1->edgePtr=NULL; if(e) e->edgePtr=e1; else graph[vertex1].edgePtr=e1; e=graph[vertex2].edgePtr; while(e&& e->edgePtr) { e=e->edgePtr; } e2=(struct edge *)malloc(sizeof(*e2)); e2->vertexIndex=vertex1; e2->edgePtr=NULL; if(e) e->edgePtr=e2; else graph[vertex2].edgePtr=e2; } void printGraph() { int i; struct edge *e; for(i=0;i<vertexCount;i++) { printf("%d",i); e=graph[i].edgePtr; while(e) { printf("->%d",e->vertexIndex); e=e->edgePtr; } printf(" "); } } int main() { InsertVertex(1); InsertVertex(2); InsertVertex(3); InsertVertex(4); InsertVertex(5); insertEdge(0,1); insertEdge(0,2); insertEdge(1,3); insertEdge(1,4); insertEdge(3,5); printGraph(); return 0; } |
权重是边的属性,因此可以将其添加到边结构中。
1 2 3 4 5 6 7 | struct edge { // You can use"-1" as the default invalid weight int weight; int vertexIndex; struct edge *edgePtr; }edge; |