|
3 | 3 | // |
4 | 4 |
|
5 | 5 | #include <random> |
| 6 | +#include <queue> |
| 7 | +#include <algorithm> |
6 | 8 | #include "UndirectedGraph.h" |
| 9 | +#include "MinHeapElement.h" |
7 | 10 |
|
8 | 11 | using namespace std; |
9 | 12 |
|
@@ -145,7 +148,69 @@ void UndirectedGraph::loadRawDataToList(std::vector<int> rawData) { |
145 | 148 | // private |
146 | 149 |
|
147 | 150 | 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 | + |
149 | 214 | } |
150 | 215 |
|
151 | 216 | void UndirectedGraph::primsAlgorithmOnList() { |
|
0 commit comments