【发布时间】:2018-11-11 00:46:05
【问题描述】:
使用在 wikipedia 上找到的伪代码在邻接表表示上实现 floyd warshall 算法,创建了以下代码。该图是一个网格,所以如果它是一个 3 x 3 网格,则顶点 0 有两条边,顶点 1 有 3,而顶点 2 有两条,依此类推。
self-> 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 或类似数字。虽然没有实际计算距离。
我相信网格的末端距离图应该在数组中填充所有可能的距离,除了从顶点到自身的距离为无穷大。
【问题讨论】:
标签: c algorithm graph floyd-warshall