TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
prims_minimum_spanning_tree.cpp
1#include <iostream>
2using namespace std;
3
4#define V 4
5#define INFINITY 99999
6
7int graph[V][V] = {{0, 5, 1, 2}, {5, 0, 3, 3}, {1, 3, 0, 4}, {2, 3, 4, 0}};
8
9struct mst {
10 bool visited;
11 int key;
12 int near;
13};
14
15mst MST_Array[V];
16
17void initilize() {
18 for (int i = 0; i < V; i++) {
19 MST_Array[i].visited = false;
20 MST_Array[i].key = INFINITY; // considering INFINITY as inifinity
21 MST_Array[i].near = i;
22 }
23
24 MST_Array[0].key = 0;
25}
26
27void updateNear() {
28 for (int v = 0; v < V; v++) {
29 int min = INFINITY;
30 int minIndex = 0;
31 for (int i = 0; i < V; i++) {
32 if (MST_Array[i].key < min && MST_Array[i].visited == false &&
33 MST_Array[i].key != INFINITY) {
34 min = MST_Array[i].key;
35 minIndex = i;
36 }
37 }
38
39 MST_Array[minIndex].visited = true;
40
41 for (int i = 0; i < V; i++) {
42 if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) {
43 if (graph[minIndex][i] < MST_Array[i].key) {
44 MST_Array[i].key = graph[minIndex][i];
45 MST_Array[i].near = minIndex;
46 }
47 }
48 }
49 }
50}
51
52void show() {
53 for (int i = 0; i < V; i++) {
54 cout << i << " - " << MST_Array[i].near << "\t"
55 << graph[i][MST_Array[i].near] << "\n";
56 }
57}
58
59int main() {
60 initilize();
61 updateNear();
62 show();
63 return 0;
64}
int main()
Main function.
Graph Algorithms.