


Find the shortest path between any two nodes using the Floyd-Warshal algorithm
C There is a macro, which is defined as a piece of code or an expected value, and it will be reused whenever the user needs it. The Floyd-Walshall algorithm is the process of finding the shortest path between all pairs of vertices in a given weighted graph. The algorithm follows a dynamic programming approach to find the minimum weight graph.
Let us understand the meaning of Freud-Walschal algorithm through diagrams -

Taking vertex 1 as the source and vertex 4 as the destination, find the shortest path between them.
We have seen that there are two paths that can be connected to target vertex 4.
1 -> 4 – The edge has a weight of 5
1 -> 8 -> 3 -> 4 – The edge weight (1 2 1) is 4.
In the given graph I, we see the smallest edge connecting two vertices. So here the path between vertex 8 and vertex 3 connecting vertex 1 to vertex 4 and the edge is 4. On the other hand, there is a directed edge between vertex 1 and vertex 4, and the edge weight is 5.
Now we compare two weights, namely 4 and 5. Therefore, here 4 is the minimum weight of the graph calculated according to the Floyd Warshall algorithm.
In this article, we will use Floyd Warshall algorithm to find the shortest path between any two given nodes.
grammar
The following syntax is used in the program -
data_type[][] array_name;
parameter
data_type[][] - The data type mentioned by the user. The first array represents rows and the second array represents columns. So, this represents a two-dimensional array.
array_name - The name given to the array.
algorithm
We will start the program with the header file 'iostream' and define the macro position as 'INF' (infinity) because later it will satisfy the two-dimensional Array matrices and if-else statements.
Next, we create a global function definition named 'printPath' and accepts three parameters, namely 'parent[]', 'i' and 'j' Verify that the path exists.
Then we start the main function and store the value ‘4’ into the variable ‘V’, which represents the number of vertices. Second, store the value in the form of an adjacency matrix into the variable 'dist[V][V]'. As we know, dist[i][j] represents a 2D matrix, which defines the weight of the edge from 'i' to 'j', By storing the adjacency matrix.
Next, we are initializing the 2D array for the variable 'parent', and the size is [V][V].
By using two nested for loops, we will find the shortest path. The first for loop iterates over the rows in the matrix. Then, iterate over the columns in the matrix through the second for loop and then we will check the following condition using if-else statement -
-
If (dist[i][j] != INF && i != j) { The Chinese translation of parent[i][j] = i;}
is: parent[i][j] = i;}In the if statement, we use the 'and' (&&) operator to express two conditions. If both conditions are met, then 'i' will be stored in 'parent[i ][j]', thereby verifying that the path exists.
-
other{ The Chinese translation of parent[i][j] = -1;}
is: parent[i][j] = -1;}In the else statement, we initialize "-1" to "parent[i][j]" to verify that the path does not exist.
Now we start with three nested for loops and apply k vertices in the range 0 to V-1, with the help of this range, our shortest distance and the path will be updated. In the third nested loop we use the following condition like
In this variable we use to display each pair of vertices 'i' and 'j' w.r.t 'parent[i][j]' .
if (dist[i][j] < dist[i][k] + dist[k][j]){ dist[i][j] = dist[i][k] + dist[k][j]; parent[i][j] = parent[k][j]; }
Next, we print out the shortest distance and path of all vertex pairs by giving the following conditions
By using two nested for loops, we print the shortest distance and path.
By using the if statement under the second for loop, we will check if dist[i][j] is equal to infinity. If it is found to be infinity, print "INF", otherwise print the shortest path.
Finally, we call the function named 'printPath()' by passing three parameters (parent[i], i, and j.
Here K is updating the row and column parts of the two-dimensional array matrix, which verifies the newly updated shortest path and distance.
Example
In this program, we will use Floyd Warshall algorithm to calculate the shortest path between any two nodes.
#include <iostream> using namespace std; #define INF 1000000000 // Infinity void printPath(int parent[], int i, int j) { if (i == j) cout << i << " "; else if (parent[j] == -1) cout << "No path exists"; else { printPath(parent, i, parent[j]); cout << j << " "; } } int main() { int V = 4; // V represent number of vertices int dist[V][V] = {{0, 2, INF, 4}, {6, 0, 5, 3}, {INF, 10, 0, 1}, {7, 9, 8, 0}}; // Represent the graph using adjacency matrix // Apply the Floyd Warshall algorithm to find the shortest paths int parent[V][V]; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][j] != INF && i != j) parent[i][j] = i; else parent[i][j] = -1; } } // update the path and distance using the k vertex range from 0 to V-1. for (int k = 0; k < V; k++) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; parent[i][j] = parent[k][j]; } } } } // Print shortest distances and paths between all pairs of vertices for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { cout << "The Shortest distance between " << i << " and " << j << " is "; if (dist[i][j] == INF) cout << "INF "; else cout << dist[i][j] << " "; cout << "and the shortest path is:- "; printPath(parent[i], i, j); cout << endl; } } return 0; }
输出
The Shortest distance between 0 and 0 is 0 and the shortest path is:- 0 The Shortest distance between 0 and 1 is 2 and the shortest path is:- 0 1 The Shortest distance between 0 and 2 is 7 and the shortest path is:- 0 1 2 The Shortest distance between 0 and 3 is 4 and the shortest path is:- 0 3 The Shortest distance between 1 and 0 is 6 and the shortest path is:- 1 0 The Shortest distance between 1 and 1 is 0 and the shortest path is:- 1 The Shortest distance between 1 and 2 is 5 and the shortest path is:- 1 2 The Shortest distance between 1 and 3 is 3 and the shortest path is:- 1 3 The Shortest distance between 2 and 0 is 8 and the shortest path is:- 2 3 0 The Shortest distance between 2 and 1 is 10 and the shortest path is:- 2 1 The Shortest distance between 2 and 2 is 0 and the shortest path is:- 2 The Shortest distance between 2 and 3 is 1 and the shortest path is:- 2 3 The Shortest distance between 3 and 0 is 7 and the shortest path is:- 3 0 The Shortest distance between 3 and 1 is 9 and the shortest path is:- 3 1 The Shortest distance between 3 and 2 is 8 and the shortest path is:- 3 2 The Shortest distance between 3 and 3 is 0 and the shortest path is:- 3
结论
我们学习了使用Floyd Warshall算法找到任意两个节点之间的最短路径的概念。我们使用邻接矩阵作为程序的输入,通过它我们找到了最短路径和距离。此外,为了更新路径和距离,我们使用了k个顶点来更新行和列。在我们的日常生活中,我们在谷歌地图上搜索最短路线或路径,从一个起点到目的地。
The above is the detailed content of Find the shortest path between any two nodes using the Floyd-Warshal algorithm. For more information, please follow other related articles on the PHP Chinese website!

There are four commonly used XML libraries in C: TinyXML-2, PugiXML, Xerces-C, and RapidXML. 1.TinyXML-2 is suitable for environments with limited resources, lightweight but limited functions. 2. PugiXML is fast and supports XPath query, suitable for complex XML structures. 3.Xerces-C is powerful, supports DOM and SAX resolution, and is suitable for complex processing. 4. RapidXML focuses on performance and parses extremely fast, but does not support XPath queries.

C interacts with XML through third-party libraries (such as TinyXML, Pugixml, Xerces-C). 1) Use the library to parse XML files and convert them into C-processable data structures. 2) When generating XML, convert the C data structure to XML format. 3) In practical applications, XML is often used for configuration files and data exchange to improve development efficiency.

The main differences between C# and C are syntax, performance and application scenarios. 1) The C# syntax is more concise, supports garbage collection, and is suitable for .NET framework development. 2) C has higher performance and requires manual memory management, which is often used in system programming and game development.

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

There are significant differences in the learning curves of C# and C and developer experience. 1) The learning curve of C# is relatively flat and is suitable for rapid development and enterprise-level applications. 2) The learning curve of C is steep and is suitable for high-performance and low-level control scenarios.

There are significant differences in how C# and C implement and features in object-oriented programming (OOP). 1) The class definition and syntax of C# are more concise and support advanced features such as LINQ. 2) C provides finer granular control, suitable for system programming and high performance needs. Both have their own advantages, and the choice should be based on the specific application scenario.

Converting from XML to C and performing data operations can be achieved through the following steps: 1) parsing XML files using tinyxml2 library, 2) mapping data into C's data structure, 3) using C standard library such as std::vector for data operations. Through these steps, data converted from XML can be processed and manipulated efficiently.

C# uses automatic garbage collection mechanism, while C uses manual memory management. 1. C#'s garbage collector automatically manages memory to reduce the risk of memory leakage, but may lead to performance degradation. 2.C provides flexible memory control, suitable for applications that require fine management, but should be handled with caution to avoid memory leakage.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools