-
Notifications
You must be signed in to change notification settings - Fork 1
/
prim.cpp
46 lines (36 loc) · 1.14 KB
/
prim.cpp
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
#include<iostream>
using namespace std;
int main()
{
int G[6][6] = { {0 , 3 , 999, 999, 6 , 5 },
{3 , 0 , 1 , 999, 999, 4 },
{999, 1 , 0 , 6 , 999, 4 },
{999, 999, 6 , 0 , 8 , 5 },
{6 , 999, 999, 8 , 0 , 2 },
{5 , 4 , 4 , 5 , 2 , 0 } };
int visited[6] = {0, 0, 0, 0, 0, 0};
int min, u, v, cost = 0;
//Start from first node
visited[0] = 1;
for(int i = 0; i < 6-1; ++i)
{
min = 999;
//Find nearest unvisited node from a visited node
for(int j = 0; j < 6; ++j)
if(visited[j] == 1)
for(int k = 0; k < 6; ++k)
if(visited[k] != 1)
if(G[j][k] < min)
{
min = G[j][k];
u = j;
v = k;
}
//Mark as visited and display the edge
visited[v] = 1;
cost += G[u][v];
cout<<v<<"-->"<<u<<"\n";
}
cout<<"Total cost: "<<cost;
return 0;
}