TheAlgorithms-C-Plus-Plus/greedy_algorithms/Prims Minimum Spanning Tree.cpp

80 lines
1.2 KiB
C++
Raw Normal View History

2017-02-27 15:20:03 +05:30
#include <iostream>
using namespace std;
2017-02-27 00:03:23 +05:30
#define V 4
2017-02-27 15:20:03 +05:30
#define INFINITY 99999
int graph[V][V] = {
{0, 5, 1, 2},
{5, 0, 3, 3},
{1, 3, 0, 4},
2019-08-21 10:10:08 +08:00
{2, 3, 4, 0}};
2017-02-27 15:20:03 +05:30
struct mst
2017-02-27 00:03:23 +05:30
{
2017-02-27 15:20:03 +05:30
bool visited;
int key;
int near;
};
2017-02-27 00:03:23 +05:30
2017-02-27 15:20:03 +05:30
mst MST_Array[V];
2017-02-27 00:03:23 +05:30
2017-02-27 15:20:03 +05:30
void initilize()
{
for (int i = 0; i < V; i++)
{
2019-08-21 10:10:08 +08:00
MST_Array[i].visited = false;
MST_Array[i].key = INFINITY; // considering INFINITY as inifinity
MST_Array[i].near = i;
2017-02-27 15:20:03 +05:30
}
2019-08-21 10:10:08 +08:00
MST_Array[0].key = 0;
2017-02-27 00:03:23 +05:30
}
2017-02-27 15:20:03 +05:30
void updateNear()
2017-02-27 00:03:23 +05:30
{
2017-02-27 15:20:03 +05:30
for (int v = 0; v < V; v++)
{
2019-08-21 10:10:08 +08:00
int min = INFINITY;
int minIndex = 0;
2017-02-27 15:20:03 +05:30
for (int i = 0; i < V; i++)
{
2019-08-21 10:10:08 +08:00
if (MST_Array[i].key < min && MST_Array[i].visited == false && MST_Array[i].key != INFINITY)
2017-02-27 15:20:03 +05:30
{
2019-08-21 10:10:08 +08:00
min = MST_Array[i].key;
minIndex = i;
2017-02-27 15:20:03 +05:30
}
}
2019-08-21 10:10:08 +08:00
MST_Array[minIndex].visited = true;
2017-02-27 15:20:03 +05:30
for (int i = 0; i < V; i++)
{
2019-08-21 10:10:08 +08:00
if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY)
2017-02-27 15:20:03 +05:30
{
2019-08-21 10:10:08 +08:00
if (graph[minIndex][i] < MST_Array[i].key)
2017-02-27 15:20:03 +05:30
{
2019-08-21 10:10:08 +08:00
MST_Array[i].key = graph[minIndex][i];
MST_Array[i].near = minIndex;
2017-02-27 15:20:03 +05:30
}
}
}
}
2017-02-27 00:03:23 +05:30
}
2017-02-27 15:20:03 +05:30
void show()
2017-02-27 00:03:23 +05:30
{
for (int i = 0; i < V; i++)
{
2019-08-21 10:10:08 +08:00
cout << i << " - " << MST_Array[i].near << "\t" << graph[i][MST_Array[i].near] << "\n";
2017-02-27 00:03:23 +05:30
}
}
int main()
{
2017-02-27 15:20:03 +05:30
initilize();
updateNear();
show();
2017-02-27 00:03:23 +05:30
return 0;
}