TheAlgorithms-C-Plus-Plus/greedy_algorithms/prims_minimum_spanning_tree.cpp

78 lines
1.5 KiB
C++
Raw Normal View History

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