Answer the question
In order to leave comments, you need to log in
What is wrong with my implementation of Dijkstra's algorithm?
There is a task: to write a program that calculates the minimum distances to the vertices in a graph using Dijkstra's method. Test on graphs with 5000 and 9000 vertices. Wrote code:
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
const int inf = 1000000;
srand(time(NULL));
int n;
cout << "Enter the number of vertices:" << endl;
cin >> n;
int **w;
w = new int *[n];
for (int i = 0; i < n; i++) {
w[i] = new int[n];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
w[i][j] = 0;
w[i][j] = rand() % 100;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) w[i][j] = 0;
else w[i][j] = w[j][i];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << setw(5) << w[i][j];
}
cout << endl;
}
int *d = new int [n];
int *v = new int [n];
for (int i = 0; i < n; i++) {
d[i] = inf;
v[i] = 1;
}
cout << "Enter the number of the vertex for which you want to find distances: ";
int ind;
cin >> ind;
ind--;
d[ind] = 0;
int minIndex, min, temp, counter = 0;
do {
minIndex = inf;
min = inf;
for (int i = 0; i < n; i++) {
if((v[i] == 1) && (d[i] < min)) {
min = d[i];
minIndex = i;
}
}
if (minIndex != inf) {
for (int i = 0; i < n; i++) {
if (w[minIndex][i] > 0) {
temp = min + w[minIndex][i];
if (temp < d[i]) {
d[i] = temp;
}
}
counter++;
}
v[minIndex] = 0;
}
} while (minIndex < inf);
for (int i = 0; i < n; i++) {
cout << setw(5) << d[i];
}
cout << endl;
cout << "Number of iterations: " << counter << endl;
system("pause");
return 0;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question