-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrim.cpp
More file actions
69 lines (53 loc) · 1.24 KB
/
Prim.cpp
File metadata and controls
69 lines (53 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include "Prim.hpp"
Graphe prim(Graphe g, int s){
int nb = g.noeuds.size();
double coute[nb];
int pred[nb];
for(int i = 0; i < nb; i++){
coute[i] = numeric_limits<double>::infinity();
pred[i] = -1;
}
coute[s] = 0;
vector<int> F;
for(int i = 0; i < nb; i++){
F.push_back(i);
}
while(F.size() != 0){
double valeMin = numeric_limits<double>::infinity();
int u = -1;
for(int i : F){
if(valeMin > coute[i]){
valeMin = coute[i];
u = i;
}
}
if(u != -1){
auto it = find(F.begin(), F.end(), u);
F.erase(it);
}else{
cout << "une erreur est survenus dans Prim ligne 31"<< endl;
}
vector<int> v = g.getNoeud(u)->getNeighborsNames();
for(int neighbor: v){
auto it = find(F.begin(), F.end(), neighbor);
double w = g.getEdge(u, neighbor)->getValue();
if(it != F.end() && w< coute[neighbor]){
coute[neighbor] = w;
pred[neighbor] = u;
}
}
}
Graphe t;
Noeud* n = nullptr;
for(int i = 0; i < nb; i++){
n = new Noeud(i);
t.addNoeud(n);
}
for (int i = 0; i < nb; i++) {
int parentIndex = pred[i];
if (parentIndex != -1) {
t.addEdge(t.getNoeud(parentIndex), t.getNoeud(i), g.getEdge(parentIndex, i)->getValue());
}
}
return t;
}