-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathprim.c
More file actions
88 lines (72 loc) · 1.65 KB
/
Copy pathprim.c
File metadata and controls
88 lines (72 loc) · 1.65 KB
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
81
82
83
84
85
86
87
88
/* prim.c
*
* Compute minimum spanning tree of graphs via Dijkstra/Prim's algorithm
*
* 2015-05-11 23:26
* Altered by James Shi
*/
#include <stdlib.h>
#include "bool.h"
#include "graph.h"
#define MAXINT 1000007
int parent[MAXV+1]; /* discovery relation */
void print_edge(int v)
{
printf("new edge (%d, %d)\n", parent[v], v);
}
void prim(graph *g, int start)
{
int i;
edgenode *p;
bool intree[MAXV+1]; /* is the vertex in the tree yet? */
int distance[MAXV+1]; /* cost of adding to tree */
int v; /* current vertex to process */
int w; /* candidate next vertex */
int weight; /* edge weight */
int dist; /* best current distance from start */
for (i=1; i<=g->nvertices; ++i) {
intree[i] = FALSE;
parent[i] = -1;
distance[i] = MAXINT;
}
distance[start] = 0;
v = start;
while (intree[v] == FALSE) {
intree[v] = TRUE;
// print the new edge
print_edge(v);
p = g->edges[v];
while (p != NULL) {
w = p->y;
weight = p->weight;
if ((distance[w] > weight) && (intree[w] == FALSE)) {
distance[w] = weight;
parent[w] = v;
}
p = p->next;
}
v = 1;
dist = MAXINT;
for (i=1; i<=g->nvertices; ++i) {
if (dist > distance[i] && intree[i] == FALSE) {
dist = distance[i];
v = i;
}
}
}
}
int main()
{
graph g;
int i;
read_weighted_graph(&g, FALSE);
printf("\n");
print_weighted_graph(&g);
printf("Out of Prim:\n");
prim(&g, 1);
// for(i=1; i<=g.nvertices; ++i) {
// find_path(1, i, parent);
// }
printf("\n");
return 0;
}