Skip to content
This repository was archived by the owner on May 27, 2019. It is now read-only.

Commit e56abb4

Browse files
committed
Add Prim's algorithm on matrix
1 parent de67899 commit e56abb4

1 file changed

Lines changed: 66 additions & 1 deletion

File tree

UndirectedGraph.cpp

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
//
44

55
#include <random>
6+
#include <queue>
7+
#include <algorithm>
68
#include "UndirectedGraph.h"
9+
#include "MinHeapElement.h"
710

811
using namespace std;
912

@@ -145,7 +148,69 @@ void UndirectedGraph::loadRawDataToList(std::vector<int> rawData) {
145148
// private
146149

147150
void UndirectedGraph::primsAlgorithmOnMatrix() {
148-
throw "Algorytm jeszcze nie zaimplementowany!";
151+
// prepare vector for output
152+
vector<vector<int>> minimumSpanningTree;
153+
int numberOfVertices = incidenceMatrix[0].size();
154+
vector<int> foundVertices;
155+
priority_queue<MinHeapElement, vector<MinHeapElement>, MinHeapElementComparator> queue;
156+
157+
// take first vertex
158+
int vertexID = 0;
159+
int edgeEnd;
160+
int edgeValue;
161+
int i;
162+
int j;
163+
164+
foundVertices.push_back(vertexID);
165+
166+
do {
167+
// look for edges from first vertices
168+
for (auto &row : incidenceMatrix) {
169+
if (row[vertexID] > 0) {
170+
edgeValue = row[vertexID];
171+
i = 0;
172+
edgeEnd = -1;
173+
for (auto &v : row) {
174+
if (i == vertexID) {
175+
i++;
176+
continue;
177+
}
178+
if (v > 0) {
179+
edgeEnd = i;
180+
}
181+
i++;
182+
}
183+
184+
if (edgeEnd == -1)
185+
throw "Nieznany blad!"; // should never be thrown
186+
187+
queue.push(MinHeapElement(vertexID, edgeEnd, edgeValue));
188+
189+
}
190+
}
191+
192+
do {
193+
MinHeapElement element = queue.top();
194+
edgeEnd = element.getEdgeEnd();
195+
edgeValue = element.getEdgeValue();
196+
} while (find(foundVertices.begin(), foundVertices.end(), edgeEnd) != foundVertices.end());
197+
198+
foundVertices.push_back(edgeEnd);
199+
200+
minimumSpanningTree.emplace_back();
201+
minimumSpanningTree[j].resize(numberOfVertices);
202+
203+
minimumSpanningTree[j][vertexID] = edgeValue;
204+
minimumSpanningTree[j][edgeEnd] = edgeValue;
205+
206+
vertexID = edgeEnd;
207+
j++;
208+
209+
} while (foundVertices.size() < numberOfVertices && queue.size() > 0);
210+
211+
if (foundVertices.size() < numberOfVertices)
212+
throw "Graf niespojny!";
213+
149214
}
150215

151216
void UndirectedGraph::primsAlgorithmOnList() {

0 commit comments

Comments
 (0)