Table of Contents
usage instructions
Greedy Algorithm
algorithm
Example
Output
Floyd−Warshall algorithm with marginal inversion cost
in conclusion
Home Backend Development C++ Checks whether the path between two nodes in the given graph represents the shortest path

Checks whether the path between two nodes in the given graph represents the shortest path

Sep 07, 2023 pm 06:57 PM
node path picture

Checks whether the path between two nodes in the given graph represents the shortest path

To check if a given path between two centers of a graph conforms to the shortest path, you can combine the entire edge weights along the given path with the same center by using a reliable shortest path The shortest distance between them is calculated using a comparative method, such as the Dijkstra calculation or the Floyd−Warshall calculation. If all edge weights on a given path match the most limited deletion, then it represents the simplest path. Also: If the overall edge weight is more prominent than the shortest distance, it indicates that there is a short distance between the two centers in the graph.

usage instructions

  • Dijkstra’s algorithm

  • Floyd−Warshall algorithm with marginal inversion cost

Greedy Algorithm

Dijkstra's calculation is perhaps a popular graph traversal calculation used to find the most limited path between a source center and all other centers in a graph. In the case of checking whether a given path between two centers is related to the most finite path, Dijkstra's calculation can be used to calculate the most finite separation between these centers. By running Dijkstra's calculation from the starting hub, we get the most finite intervals for all other hubs. If a given route matches the most limited distance between two hubs, then it represents a substantial and shortest route. Others: If the given route is longer than the calculated shortest distance, it indicates that a shorter route exists in the chart.

algorithm

  • Create the shortest path (graph, source, destination):

  • Initialize a set of "past" to store the distance to the center, and initialize a word reference interval to store the most limited distance.

  • Set the source hub's spacing to infinity and all other hubs' spacing to infinity in the separator dictionary.

  • Although there are unvisited nodes,

  • a. The center with the smallest distance from the separator word reference is selected and marked as visited.

  • b. For each neighbor hub of the current node:

  • The temporary interval is calculated by adding the edge weight to the distance of the current node.

  • If the condition spacing is smaller than the storage spacing, then the inspection distance.

  • Returns true if the shortest distance from source to destination in separation breaks even with the given path length (the given path represents the shortest path). Otherwise, return false.

  • This calculation utilizes Dijkstra's method to calculate the shortest interval and then compares the shortest distance from the source to the destination with the given path length to determine if it is the shortest path.

Example

#include <iostream>
#include <vector>
#include <queue>
#include <limits>
using namespace std;

const int INF = numeric_limits<int>::max();

bool shortestPath(vector<vector<pair<int, int>>>& graph, int source, int destination, int pathLength) {
    int numNodes = graph.size();
    vector<int> distances(numNodes, INF);
    distances[source] = 0;

    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    pq.emplace(0, source);

    while (!pq.empty()) {
        int u = pq.top().second;
        int dist = pq.top().first;
        pq.pop();

        if (dist > distances[u])
            continue;

        for (auto& neighbor : graph[u]) {
            int v = neighbor.first;
            int weight = neighbor.second;

            if (dist + weight < distances[v]) {
                distances[v] = dist + weight;
                pq.emplace(distances[v], v);
            }
        }
    }

    return (distances[destination] == pathLength);
}

int main() {
    int numNodes = 6;
    vector<vector<pair<int, int>>> graph(numNodes);

    // Build the graph
    graph[0].emplace_back(1, 2);
    graph[0].emplace_back(2, 5);
    graph[1].emplace_back(3, 4);
    graph[1].emplace_back(4, 1);
    graph[2].emplace_back(3, 2);
    graph[3].emplace_back(4, 3);
    graph[3].emplace_back(5, 6);
    graph[4].emplace_back(5, 2);

    int source = 0;
    int destination = 5;
    int pathLength = 8;

    bool isShortestPath = shortestPath(graph, source, destination, pathLength);

    if (isShortestPath)
        cout << "The given path represents a shortest path." << endl;
    else
        cout << "The given path does not represent a shortest path." << endl;

    return 0;
}

Copy after login

Output

The given path does not represent a shortest path.
Copy after login

Floyd−Warshall algorithm with marginal inversion cost

The Floyd-Warshall calculation is a dynamically programmed calculation that finds the shortest path between all pairs of centers in a graph. In the case of checking whether a given path between two centers is related to the most limited path, the Floyd-Warshall calculation can be used to calculate the shortest separation between all sets of centers in the graph. By comparing the calculated shortest distance to all edge weights on a given path, we can determine whether a given path involves the most limited path. If the overall edge weight matches the shortest separation, then the given path at this time is probably the most limited path between two centers in the graph.

algorithm

  • Make a 2D lattice measuring numNodes x numNodes and initialize it to infinity (INF) for all node sets.

  • Set the corner-to-corner addition of dist to 0.

  • For each coordination edge (u, v) with weight w in the graph, completely modify dist[u][v] to w and modify dist[v][u] to w w_reversal, where w_reversal is obtained by reversing the edge (v, u).

  • Perform the Floyd−Warshall calculation after the canned loop:

  • For each halfway hub from numNodes to 1, do the following:

  • For each aggregate of hubs i and j from numNodes to 1, refine dist[i][j] to the minimum of the following values:

  • Distance[i][j]

  • Distance[i][k]Distance[k][j]

  • After the calculation is complete, dist will contain the most limited separation between all hub groups, taking into account edge inversion costs.

  • To check if a given route between two hubs (source and destination) is the shortest route, compare the length of the given route with the distance [source][destination]. If so, the given way is the most limited way.

Example

#include <iostream>
#include <vector>
using namespace std;

const int INF = 1e9;

void floydWarshall(vector<vector<int>>& graph, int numNodes) {
    vector<vector<int>> dist(graph); // Distance matrix initialized with the graph

    for (int k = 0; k < numNodes; k++) {
        for (int i = 0; i < numNodes; i++) {
            for (int j = 0; j < numNodes; j++) {
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
            }
        }
    }

    // Printing the shortest distances
    cout << "Shortest distances between all pairs of nodes:" << endl;
    for (int i = 0; i < numNodes; i++) {
        for (int j = 0; j < numNodes; j++) {
            if (dist[i][j] == INF)
                cout << "INF ";
            else
                cout << dist[i][j] << " ";
        }
        cout << endl;
    }
}

int main() {
    int numNodes = 4; // Number of nodes

    // Adjacency matrix representation of the graph with edge weights and edge reversal costs
    vector<vector<int>> graph = {
        {0, 5, INF, 10},
        {INF, 0, 3, INF},
        {INF, INF, 0, 1},
        {INF, INF, INF, 0}
    };

    floydWarshall(graph, numNodes);

    return 0;
}
Copy after login

Output

Shortest distances between all pairs of nodes:
0 5 8 9 
INF 0 3 4 
INF INF 0 1 
INF INF INF 0 
Copy after login

in conclusion

This article explores how to check whether a given path between two centers of a graph represents the most finite path. It illustrates two methods: the Dijkstra calculation and the Floyd-Warshall calculation for obtaining edge inversions. Code usage in C illustrates these calculations. It also briefly explains calculations and their uses. This article is intended to help readers understand how to find the most limited method in a diagram and determine whether a given method is undoubtedly the simplest.

The above is the detailed content of Checks whether the path between two nodes in the given graph represents the shortest path. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Where are themes located in Windows 11? Where are themes located in Windows 11? Aug 01, 2023 am 09:29 AM

Windows 11 has so many customization options, including a range of themes and wallpapers. While these themes are aesthetic in their own way, some users still wonder where they stand in the background on Windows 11. This guide will show you the different ways to access the location of your Windows 11 theme. What is the Windows 11 default theme? The default theme background of Windows 11 is an abstract royal blue flower blooming with a sky blue background. This background is one of the most popular, thanks to the anticipation before the release of the operating system. However, the operating system also comes with a range of other backgrounds. Therefore, you can change the Windows 11 desktop theme background at any time. Themes are stored in Windo

How to fix error: Main class not found or loaded in Java How to fix error: Main class not found or loaded in Java Oct 26, 2023 pm 11:17 PM

This video cannot be played due to a technical error. (Error Code: 102006) This guide provides simple fixes for this common problem and continue your coding journey. We will also discuss the causes of Java errors and how to prevent it in the future. What is "Error: Main class not found or loaded" in Java? Java is a powerful programming language that enables developers to create a wide range of applications. However, its versatility and efficiency come with a host of common mistakes that can occur during development. One of the interrupts is Error: Main class user_jvm_args.txt not found or loaded, which occurs when the Java Virtual Machine (JVM) cannot find the main class to execute a program. This error acts as a roadblock even in

Different uses of slashes and backslashes in file paths Different uses of slashes and backslashes in file paths Feb 26, 2024 pm 04:36 PM

A file path is a string used by the operating system to identify and locate a file or folder. In file paths, there are two common symbols separating paths, namely forward slash (/) and backslash (). These two symbols have different uses and meanings in different operating systems. The forward slash (/) is a commonly used path separator in Unix and Linux systems. On these systems, file paths start from the root directory (/) and are separated by forward slashes between each directory. For example, the path /home/user/Docume

How to use Prim's algorithm in C++ How to use Prim's algorithm in C++ Sep 20, 2023 pm 12:31 PM

Title: Use of Prim algorithm and code examples in C++ Introduction: Prim algorithm is a commonly used minimum spanning tree algorithm, mainly used to solve the minimum spanning tree problem in graph theory. In C++, Prim's algorithm can be used effectively through reasonable data structures and algorithm implementation. This article will introduce how to use Prim's algorithm in C++ and provide specific code examples. 1. Introduction to Prim algorithm Prim algorithm is a greedy algorithm. It starts from a vertex and gradually expands the vertex set of the minimum spanning tree until it contains

What is the difference in the 'My Computer' path in Win11? Quick way to find it! What is the difference in the 'My Computer' path in Win11? Quick way to find it! Mar 29, 2024 pm 12:33 PM

What is the difference in the "My Computer" path in Win11? Quick way to find it! As the Windows system is constantly updated, the latest Windows 11 system also brings some new changes and functions. One of the common problems is that users cannot find the path to "My Computer" in Win11 system. This was usually a simple operation in previous Windows systems. This article will introduce how the paths of "My Computer" are different in Win11 system, and how to quickly find them. In Windows1

How to find the storage path of RPM files in Linux system? How to find the storage path of RPM files in Linux system? Mar 14, 2024 pm 04:42 PM

In Linux systems, RPM (RedHatPackageManager) is a common software package management tool used to install, upgrade and delete software packages. Sometimes we need to find the storage path of an installed RPM file for search or other operations. The following will introduce how to find the storage path of the RPM file in the Linux system, and provide specific code examples. First, we can use the rpm command to find the installed RPM package and its storage path. Open

Linux kernel source code storage path analysis Linux kernel source code storage path analysis Mar 14, 2024 am 11:45 AM

The Linux kernel is an open source operating system kernel whose source code is stored in a dedicated code repository. In this article, we will analyze the storage path of the Linux kernel source code in detail, and use specific code examples to help readers better understand. 1. Linux kernel source code storage path The Linux kernel source code is stored in a Git repository called linux, which is hosted at [https://github.com/torvalds/linux](http

In JavaFX, what are the different path elements? In JavaFX, what are the different path elements? Aug 28, 2023 pm 12:53 PM

The javafx.scene.shape package provides some classes with which you can draw various 2D shapes, but these are just primitive shapes like lines, circles, polygons and ellipses etc... So if you want to draw complex For custom shapes, you need to use the Path class. Path class Path class You can draw custom paths using this geometric outline that represents a shape. To draw custom paths, JavaFX provides various path elements, all of which are available as classes in the javafx.scene.shape package. LineTo - This class represents the path element line. It helps you draw a straight line from the current coordinates to the specified (new) coordinates. HlineTo - This is the table

See all articles