Check if Alternate Paths Exists from U toV with Smaller Individual Weight in a given Graph


In graph analysis, one common job is determining whether or not there is a path from node U to node V that has a lower total weight than the one currently being used. Checking for other paths between nodes that have a lower total weight than the current path is what this entails.

The Floyd−Warshall and Bellman−Ford algorithms are two methods that are often utilised. The Floyd−Warshall technique calculates the cost of traversing any pair of nodes in order to compare various routes through a graph. However, by determining the shortest routes from a single source node to all other nodes, the Bellman−Ford approach can locate alternate pathways with lower weights.

Methods Used

  • Floyd−Warshall algorithm

  • Bellman−Ford algorithm

Floyd−Warshall Algorithm

By repeatedly evaluating intermediate nodes and updating the path costs, this method determines the shortest path costs between all pairs of nodes. The Floyd−Warshall technique is useful for dense networks due to its ability to quickly and accurately determine the shortest pathways between any two given nodes.

Algorithm

  • Initialise a 2D matrix cost of size n x n to record shortest path costs.

  • Set cost diagonals to 0.

  • Update cost matrix with graph, where cost[u][v] denotes edge weight from node u to node v. Assign a specific value (e.g., INF) to cells without direct edges.

Example

#include <iostream>
#include <vector>
#include <climits>

using namespace std;

#define INF INT_MAX

// Structure to represent an edge
struct Edge {
    int src, dest, weight;
};

// Function to check if alternate path exists from U to V with smaller individual weight using Floyd-Warshall algorithm
bool hasAlternatePathFloydWarshall(const vector<vector<int>>& graph, int U, int V) {
    int n = graph.size();

    // Initialize a 2D vector to store the shortest path costs
    vector<vector<int>> cost(n, vector<int>(n, INF));

    // Initialize the diagonal elements as 0
    for (int i = 0; i < n; i++) {
        cost[i][i] = 0;
    }

    // Update the cost matrix with the given graph
    for (int u = 0; u < n; u++) {
        for (int v = 0; v < n; v++) {
            if (graph[u][v] != INF) {
                cost[u][v] = graph[u][v];
            }
        }
    }

    // Floyd-Warshall algorithm to find all shortest paths
    for (int k = 0; k < n; k++) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (cost[i][k] != INF && cost[k][j] != INF && cost[i][k] + cost[k][j] < cost[i][j]) {
                    cost[i][j] = cost[i][k] + cost[k][j];
                }
            }
        }
    }

    // Check if there is an alternate path from U to V with smaller individual weight
    if (cost[U][V] != INF) {
        for (int k = 0; k < n; k++) {
            if (k != U && k != V && graph[U][k] != INF && graph[k][V] != INF && graph[U][k] + graph[k][V] < cost[U][V]) {
                return true;
            }
        }
    }

    return false;
}

// Function to check if alternate path exists from U to V with smaller individual weight using Bellman-Ford algorithm


int main() {
    // Example graph
    int numNodes = 5;
    vector<vector<int>> graph = {
        {0, 1, INF, 1, 5},
        {INF, 0, 3, 2, INF},
        {INF, INF, 0, INF, 1},
        {INF, INF, INF, 0, INF},
        {INF, INF, INF, INF, 0}
    };
    vector<Edge> edges = {
        {0, 1, 1},
        {0, 3, 1},
        {0, 4, 5},
        {1, 2, 3},
        {1, 3, 2},
        {2, 4, 1}
    };
    int U = 0;
    int V = 4;

    bool alternatePathExistsFW = hasAlternatePathFloydWarshall(graph, U, V);


    if (alternatePathExistsFW) {
        cout << "Alternate path exists from U to V with smaller individual weight using Floyd-Warshall." << endl;
    } else {
        cout << "No alternate path exists from U to V with smaller individual weight using Floyd-Warshall." << endl;
    }


    return 0;
}

Output

No alternate path exists from U to V with smaller individual weight using Floyd−Warshall.

Bellman−Ford Method

The Bellman−Ford method is a well−known example of a single−source shortest path algorithm, and it is particularly useful since it can process networks with negative edge weights and identify negative weight cycles. This approach relies on dynamic programming techniques to determine the shortest pathways by progressively loosening their constraints. At the outset of the procedure, the distance between the source node and each of the other nodes is set to infinity. Then, it iteratively relaxes all the edges to shorten the pathways until the best ones are found. Despite its adaptability, the Bellman−Ford technique may not be as effective as other algorithms for dense networks due to its temporal complexity. This is especially true for graphs with negative edge weights.

Algorithm

  • Create an edge structure containing src, dest, and weight properties.

  • Create a method hasAlternatePath that takes a vector of Edge objects edges, numNodes, and the source and destination nodes U and V and returns a boolean value.

  • Initialise a vector dist of size numNodes and set all members to maximum except the source node U, which is 0.

Example

#include <iostream>
#include <vector>
#include <climits>

using namespace std;

#define INF INT_MAX

// Structure to represent an edge
struct Edge {
    int src, dest, weight;
};


// Function to check if alternate path exists from U to V with smaller individual weight using Bellman-Ford algorithm
bool hasAlternatePathBellmanFord(const vector<Edge>& edges, int numNodes, int U, int V) {
    vector<int> dist(numNodes, INF);
    dist[U] = 0; // Set the distance of the source node to 0

    // Relax all edges (numNodes - 1) times
    for (int i = 0; i < numNodes - 1; i++) {
        for (const auto& edge : edges) {
            int u = edge.src;
            int v = edge.dest;
            int weight = edge.weight;

            if (dist[u] != INF && dist[u] + weight < dist[v]) {
                dist[v] = dist[u] + weight;
            }
        }
    }

    // Check if there is an alternate path from U to V with smaller individual weight
    if (dist[V] != INF) {
        for (const auto& edge : edges) {
            int u = edge.src;
            int v = edge.dest;
            int weight = edge.weight;

            if (dist[u] != INF && dist[u] + weight < dist[v]) {
                return true;
            }
        }
    }

    return false;
}

int main() {
    // Example graph
    int numNodes = 5;
    vector<vector<int>> graph = {
        {0, 1, INF, 1, 5},
        {INF, 0, 3, 2, INF},
        {INF, INF, 0, INF, 1},
        {INF, INF, INF, 0, INF},
        {INF, INF, INF, INF, 0}
    };
    vector<Edge> edges = {
        {0, 1, 1},
        {0, 3, 1},
        {0, 4, 5},
        {1, 2, 3},
        {1, 3, 2},
        {2, 4, 1}
    };
    int U = 0;
    int V = 4;

 
    bool alternatePathExistsBF = hasAlternatePathBellmanFord(edges, numNodes, U, V);



    if (alternatePathExistsBF) {
        cout << "Alternate path exists from U to V with smaller individual weight using Bellman-Ford." << endl;
    } else {
        cout << "No alternate path exists from U to V with smaller individual weight using Bellman-Ford." << endl;
    }

    return 0;
}

Output

No alternate path exists from U to V with smaller individual weight using Bellman−ford

Conclusion

In conclusion, determining if a different path from U to V with less individual weight exists in a particular network is a significant problem in graph analysis. The Floyd−Warshall and the Bellman−Ford are two effective solutions to this problem.The Floyd−Warshall technique may be used to find all of the shortest path costs between any two nodes in a graph. Because it functions with both directed and undirected graphs, it is a versatile option. The Bellman−Ford technique, in contrast, is designed to find single−source shortest routes and is capable of handling graphs with negative edge weights as well as spotting negative weight cycles.

Updated on: 13-Jul-2023

41 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements