使用维基百科上的伪代码在邻接列表表示中实现floyd warshall算法,创建了以下代码。图是一个网格,所以如果它是一个3 x 3网格顶点0有两条边,顶点1有3,而顶点2有2,依此类推。
自> V =图中的顶点数!!
void floyd(Graph *self, int** dist, int** next)
{
int i, j, k;
EdgeNodePtr current;
current = malloc(sizeof(current));
for (i = 0; i < self->V; i++)
{
for (j = 0; j < self->V; j++) {
dist[i][j] = INT_MAX; // Sets all minimun distances to infintiy
next[i][j] = -1; // Sets all next vertex to a non existant vertex
}
}
for (i = 0; i < self->V; i++)
{
for (j = 0; j < self->V; j++)
{
current = self->edges[i].head;
while (current != NULL) // Cycles through all the edges in edgelist
{
if (current->edge.to_vertex == j) // If an edge to the correct vertex is found then adds distance
{
dist[i][j] = current->edge.weight;
next[i][j] = j; // Updates next node
}
current = current->next;
}
}
}
PRINT
// Standard implemnation of floyds algorithm
for (k = 0; k < self->V; k++)
{
for (i = 0; i < self->V; i++)
{
for (j = 0; j < self->V; j++)
{
if (dist[i][j] > dist[i][k] + dist[k][j])
{
dist[i][j] = dist[i][k] + dist[k][j];
next[i][j] = next[i][k];
}
}
}
}
PRINT
}
所发生的是边缘全部正确插入距离阵列,通过简单的打印进行检查。算法运行时会遇到问题,它将所有距离转换为INT_MINS或类似的数字。虽然没有实际计算距离。
我相信网格的终点距离图应该在数组中填充每个可能的距离,除了从顶点到自身的距离为无穷大。
答案 0 :(得分:2)
你需要注意int溢出。 Wikipedia pseudocode(在此答案的底部)使用&#34; infinity&#34;其中&#34;无穷大+(任何有限的)=无穷大&#34;。但是,当您使用INT_MAX
来表示&#34; infinity&#34;时,情况并非如此。由于溢出。尝试将if语句条件更改为:
if (dist[i][k] != INT_MAX &&
dist[k][j] != INT_MAX &&
dist[i][j] > dist[i][k] + dist[k][j]) {
这样可以避免因为向INT_MAX
添加正距离而导致int溢出。
维基百科伪代码:
1 let dist be a |V| × |V| array of minimum distances initialized to ∞ (infinity) 2 for each edge (u,v) 3 dist[u][v] ← w(u,v) // the weight of the edge (u,v) 4 for each vertex v 5 dist[v][v] ← 0 6 for k from 1 to |V| 7 for i from 1 to |V| 8 for j from 1 to |V| 9 if dist[i][j] > dist[i][k] + dist[k][j] 10 dist[i][j] ← dist[i][k] + dist[k][j] 11 end if