我正在尝试在c ++代码中实现Dijkstra算法,该算法从文本文件中找到最短的图形。文本文件包含表示有向图的矩阵。 Dijkstra算法找到从源顶点到每个其他顶点的最短路径。 我在这个c ++中尝试做的是将每个顶点用作源。我完成了代码,但如果我的代码是对的,我仍然非常怀疑。如果我做错了,你能帮我分析一下代码吗?感谢您抽出宝贵时间。
int minDistance(int dist[], bool sptSet[], int V)
{
// Initialize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;}
double dijkstra(int vertex, int **graph, int src)
{
auto start_time = chrono::high_resolution_clock::now();
int* dist = new int[vertex]; // The output array. dist[i] will hold the shortest
// distance from src to i
bool* sptSet = new bool[vertex]; // sptSet[i] will true if vertex i is included in shortest
// path tree or shortest distance from src to i is finalized
src = k;
// Initialize all distances as INFINITE and stpSet[] as false
for (int i = 0; i < vertex; i++)
{
dist[i] = INT_MAX, sptSet[i] = false;
}
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find shortest path for all vertices
for (int count = 0; count < vertex - 1; count++)
{
// Pick the minimum distance vertex from the set of vertices not
// yet processed. u is always equal to src in first iteration.
int u = minDistance(dist, sptSet, vertex);
// Mark the picked vertex as processed
sptSet[u] = true;
// Update dist value of the adjacent vertices of the picked vertex.
for (int v = 0; v < vertex; v++)
// Update dist[v] only if is not in sptSet, there is an edge from
// u to v, and total weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])
{
dist[v] = dist[u] + graph[u][v];
}
}
k++;
delete[] dist;
delete[] sptSet;
}
auto end_time = chrono::high_resolution_clock::now();
double elapsed = chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count();
return elapsed;
}