0% found this document useful (0 votes)
27 views6 pages

Floyd-Warshall Algorithm in C

The Floyd-Warshall algorithm finds the shortest paths between all pairs of vertices in a weighted graph. It works for both directed and undirected graphs, but not graphs with negative cycles. The algorithm uses dynamic programming to efficiently calculate shortest paths between all pairs of vertices in O(V^3) time by iteratively updating the graph. Pseudocode and a C implementation are provided.

Uploaded by

A H M
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views6 pages

Floyd-Warshall Algorithm in C

The Floyd-Warshall algorithm finds the shortest paths between all pairs of vertices in a weighted graph. It works for both directed and undirected graphs, but not graphs with negative cycles. The algorithm uses dynamic programming to efficiently calculate shortest paths between all pairs of vertices in O(V^3) time by iteratively updating the graph. Pseudocode and a C implementation are provided.

Uploaded by

A H M
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Warshall Algorithm:

Floyd-Warshall Algorithm is an algorithm for finding the shortest path between

all the pairs of vertices in a weighted graph. This algorithm works for both the

directed and undirected weighted graphs. But, it does not work for the graphs

with negative cycles (where the sum of the edges in a cycle is negative).This

algorithm follows the dynamic programming approach to find the shortest

paths.

CODE:

#include <stdio.h>

#include <stdlib.h>

void floydWarshall(int **graph, int n)

int i, j, k;

for (k = 0; k < n; k++)

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)

{
if (graph[i][j] > graph[i][k] + graph[k][j])

graph[i][j] = graph[i][k] + graph[k][j];

int main(void)

int n, i, j;

printf("Enter the number of vertices: ");

scanf("%d", &n);

int **graph = (int **)malloc((long unsigned) n * sizeof(int *));

for (i = 0; i < n; i++)

graph[i] = (int *)malloc((long unsigned) n * sizeof(int));

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)

{
if (i == j)

graph[i][j] = 0;

else

graph[i][j] = 100;

printf("Enter the edges: \n");

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)

printf("[%d][%d]: ", i, j);

scanf("%d", &graph[i][j]);

printf("The original graph is:\n");

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)


{

printf("%d ", graph[i][j]);

printf("\n");

floydWarshall(graph, n);

printf("The shortest path matrix is:\n");

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)

printf("%d ", graph[i][j]);

printf("\n");

return 0;

}
Example From Slide:

Shortest Path Algorithm:

Own Creating Example:

Common questions

Powered by AI

The example code from Source 1 demonstrates the process of setting up a graph for the Floyd-Warshall algorithm by first reading the number of vertices and dynamically allocating a 2D array (matrix) to represent it. It then initializes the graph by setting zero for diagonal elements (distance from a vertex to itself) and a large number (simulating infinity) for other entries, unless an edge exists, in which case it reads the edge weights from user input. This setup prepares the graph such that the algorithm can then iterate through each vertex as an intermediate point, updating path lengths and storing the shortest paths in the matrix .

The Floyd-Warshall algorithm is well-suited to finding the shortest paths in fully connected graphs because it systematically examines all pairs of vertices and updates paths, considering every possible Intermediate path. In fully connected graphs, every vertex is reachable from every other vertex which means the algorithm can effectively assess and update the shortest path information for every pair of vertices iteratively. The comprehensive consideration of each possible intermediary vertex allows the algorithm to efficiently compute the shortest paths in densely connected scenarios .

The Floyd-Warshall algorithm utilizes a 2D array (matrix) to store and update the shortest path information between vertex pairs. The matrix is initially set up with direct edge weights initialized between vertex pairs, using a large value (such as 100) for pairs without direct edges to simulate infinity, except for diagonal elements which are set to zero as the shortest path from a vertex to itself is zero. During execution, the algorithm iteratively updates this matrix by checking if an indirect path through an intermediate vertex offers a shorter route. The matrix is progressively filled with the shortest path values as intermediary points are considered and evaluated across iterations .

If the Floyd-Warshall algorithm encounters negative edge weights in a graph without cycles, it behaves normally and correctly updates the shortest paths, potentially using the negative weights to reduce path lengths as long as no cycles are formed. The negative edge weights can still lead to correct solutions because the algorithm checks each path iteratively, ensuring that the updated values are optimal for the considered vertex intermediates. This means the implications are that the algorithm remains valid and usable as long as negative cycles, which cause infinite reductions in path lengths, are absent .

Yes, the Floyd-Warshall algorithm can handle both directed and undirected graphs. This versatility affects its implementation in that it uniformly considers paths in terms of vertex pair relationships without bias towards edge directions. In the case of undirected graphs, each connection affects both corresponding entries in the adjacency matrix symmetrically, while for directed graphs the entries remain sparse depending on directionality. Thus, implementation is straightforward across graph types since the presence of direction in graph edges doesn't alter the matrix setup or the dynamic programming routine used in path evaluation .

The Floyd-Warshall algorithm is distinguished from other shortest path algorithms like Dijkstra’s by its approach and application scope. Floyd-Warshall computes shortest paths for all pairs of vertices simultaneously and is suited for dense graphs, leveraging a simple matrix update method for path assessment through dynamic programming. In contrast, Dijkstra's algorithm is generally used for finding the shortest path from a single source to all other vertices, operating on a point-to-graph basis and utilizing a priority queue to maintain the shortest known path costs effectively. Additionally, Dijkstra's typically cannot handle graphs with negative edge weights, whereas Floyd-Warshall can, unless the graph also has negative cycles .

The Floyd-Warshall algorithm ensures finding the shortest paths in a weighted graph by considering each vertex as an intermediate point in pathfinding. It utilizes a dynamic programming approach where it iteratively updates the distance between all pairs of vertices. For every triplet of vertices (i, j, k), the algorithm checks if a path through vertex k offers a shorter path from i to j than the current recorded shortest path. If so, it updates the path length for i to j. By iterating over all possible intermediate vertices, the algorithm guarantees how it tightens up the estimate of the shortest paths gradually until it reaches the optimal solutions .

The core function of the nested loops within the Floyd-Warshall algorithm's main execution block is to iteratively update the shortest path matrix using all vertices of the graph as potential intermediate points. The outermost loop selects each vertex in turn as the current intermediate point k. The two inner loops iterate through every pair of start (i) and end (j) vertices to compare the current shortest path from i to j with the path going from i to k and then from k to j. If the new path via k is shorter, the algorithm updates the path length in the matrix for these vertices, continuously refining the matrix values towards the optimal shortest paths .

The primary limitation of the Floyd-Warshall algorithm is that it does not work for graphs that contain negative cycles. A negative cycle is a cycle in the graph where the sum of the edge weights is negative. This limitation impacts its application because in the presence of a negative cycle, the concept of a shortest path becomes ill-defined, as repeatedly traversing the negative cycle would continue reducing the path length indefinitely. Therefore, if a graph contains negative cycles, the algorithm fails to give meaningful results .

The dynamic programming strategy of the Floyd-Warshall algorithm differs from recursive strategies in that it relies on tabulation (bottom-up approach) rather than memorization or recursion (top-down approach). In Floyd-Warshall, a table is used to iteratively update shortest path estimates by considering each vertex as an intermediary and updating in a nested loop pattern. Recursive strategies often involve trees of repeated calls to solve overlapping subproblems, using memoization to store intermediate results, while dynamic programming in Floyd-Warshall involves directly utilizing previously computed results in an iterative manner to update the table of shortest paths without recursion .

You might also like