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

Commit 0e687e5

Browse files
committed
Add basic version of list algorithm
1 parent 9f06dce commit 0e687e5

1 file changed

Lines changed: 50 additions & 1 deletion

File tree

UndirectedGraph.cpp

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,5 +227,54 @@ string UndirectedGraph::primsAlgorithmOnMatrix() {
227227
}
228228

229229
string UndirectedGraph::primsAlgorithmOnList() {
230-
throw "Algorytm jeszcze nie zaimplementowany!";
230+
// prepare vector for output
231+
std::vector<std::forward_list<EdgeListElement>> minimumSpanningTree;
232+
233+
if (adjacencyList.size() == 0)
234+
throw "Graf pusty!";
235+
236+
int numberOfVertices = adjacencyList.size();
237+
minimumSpanningTree.resize(numberOfVertices);
238+
vector<int> foundVertices;
239+
priority_queue<MinHeapElement, vector<MinHeapElement>, MinHeapElementComparator> queue;
240+
241+
// take first vertex
242+
int vertexID = 0;
243+
int edgeEnd;
244+
int edgeValue;
245+
int i;
246+
int j = 0;
247+
248+
foundVertices.push_back(vertexID);
249+
250+
do {
251+
// look for edges from first vertices
252+
for (auto& element : adjacencyList[vertexID]) {
253+
queue.push(MinHeapElement(vertexID, element.edgeEnd, element.value));
254+
}
255+
256+
do {
257+
if (queue.empty()) // jesli kolejka pusta, wywal sie
258+
throw "Graf niespojny!";
259+
MinHeapElement element = queue.top();
260+
vertexID = element.getEdgeBeginning();
261+
edgeEnd = element.getEdgeEnd();
262+
edgeValue = element.getEdgeValue();
263+
queue.pop();
264+
} while (find(foundVertices.begin(), foundVertices.end(), edgeEnd) != foundVertices.end());
265+
266+
foundVertices.push_back(edgeEnd);
267+
268+
minimumSpanningTree[vertexID].push_front({edgeEnd, edgeValue});
269+
270+
vertexID = edgeEnd;
271+
j++;
272+
273+
} while (foundVertices.size() < numberOfVertices);
274+
275+
string output = "Minimalne drzewo rozpinajace\n";
276+
277+
output += printMatrix(minimumSpanningTree);
278+
279+
return output;
231280
}

0 commit comments

Comments
 (0)