Home > Backend Development > C++ > In a directed weighted graph, find the shortest path containing exactly k edges.

In a directed weighted graph, find the shortest path containing exactly k edges.

PHPz
Release: 2023-09-11 19:17:02
forward
1018 people have browsed it

In a directed weighted graph, find the shortest path containing exactly k edges.

In a coordinated weighted graph, the problem of finding the shortest path with exactly k edges involves determining the path with the smallest weight when navigating exactly k edges. This will be achieved by employing dynamic programming strategies, such as employing 3D frameworks to store minimal weights in all conceivable ways. The calculation is repeated at vertices and edges, adjusting the minimum weight at each step. By considering all possible ways of having exactly k edges, the calculation can distinguish the most limited way of having k edges in the graph.

usage instructions

  • Naive recursive method

  • Dijkstra’s algorithm with edge constraints

Naive recursive method

Naive recursive methods can be an important and clear strategy for problem solving, which involves decomposing complex problems into smaller sub-problems and solving them recursively. In this approach, the work calls itself multiple times to explore subproblems until the base case is reached. Nonetheless, it can be wasteful for larger problems due to double counting and covering subproblems. It requires optimization methods such as memory or energy programming. Gullible recursive methods are easy to obtain and implement, but may suffer from exponential time complexity. It is often used to solve small-scale problems or as a starting point for more optimal calculations.

algorithm

  • Represents the working shortest path (graph, u, v, k) that takes as input a graph, a source vertex u, a target vertex v, and the number of edges k.

  • Check the basic situation:

  • a. Return if k and u break even with v (since no edges are allowed in this case).

  • the second. If k is 1 and there is an edge between u and v in the graph, its weight is returned.

  • c. If k is less than or equal to 0, return unbounded (because negative or zero edges are not allowed).

  • Initialize an infinite variable res to store the shortest path distance.

  • The graph should iterate over all vertices as follows:

  • a. If u and i do not rise to u or v, then there is an edge from u to i:

  • Call shortestPath recursively, where i is the modern source vertex, v is the target vertex, and k−1 is the number of remaining edges.

  • If the returned result is not infinite, res will be upgraded to the minimum value of res and the weight of the current edge and the recursive result.

  • Return the value of res as the most limited way to accurately separate k edges.

Example

#include <iostream>
#include <climits>

#define V 4
#define INF INT_MAX

int shortestPathWithKEdges(int graph[][V], int source, int destination, int k) {
    // Base cases
    if (k == 0 && source == destination)
        return 0;
    if (k == 1 && graph[source][destination] != INF)
        return graph[source][destination];
    if (k <= 0)
        return INF;

    // Initialize result
    int shortestPathDistance = INF;

    // Explore all adjacent vertices of the source vertex
    for (int i = 0; i < V; i++) {
        if (graph[source][i] != INF && source != i && destination != i) {
            int recursiveDistance = shortestPathWithKEdges(graph, i, destination, k - 1);
            if (recursiveDistance != INF)
                shortestPathDistance = std::min(shortestPathDistance, graph[source][i] + recursiveDistance);
        }
    }

    return shortestPathDistance;
}

int main() {
    int graph[V][V] = {
        {0, 10, 3, 2},
        {INF, 0, INF, 7},
        {INF, INF, 0, 6},
        {INF, INF, INF, 0}
    };
    int source = 0, destination = 3, k = 2;
    std::cout << "Weight of the shortest path is " << shortestPathWithKEdges(graph, source, destination, k) << std::endl;
    return 0;
}

Copy after login

Output

Weight of the shortest path is 9
Copy after login

Dijkstra's algorithm with edge constraints

Dijkstra's algorithm with edge constraints is a graph traversal calculation that identifies the shortest path between a source vertex and all other vertices on the graph. It takes into account limits or constraints on the edges of the graph, such as the most or least extreme edge weights. This calculation retains the required vertex lines and iteratively selects the fewest vertices to remove. At this point, if a shorter path is found, it relaxes adjacent vertices by increasing the distance between them. This preparation continues until all vertices have been visited. Dijkstra's algorithm with edge commands guarantees that the chosen way satisfies the required edge constraints while finding the most limited way

algorithm

  • Create Dijkstra's artwork using the following parameters

  • Graph: Input graph with vertices and edges

    Source: starting vertex of the most limited path

    Constraints: Limitations or obstacles at the edge

    Initialize a set of vanished vertices and a demand line to store the vertices and their distances.

  • Create a deletion cluster and set deletion to terminability for all vertices except the source vertex, which is set to 0.

  • Arrange the source vertices into the desired rows by their distance.

  • Although the demand pipeline is not purgeable, please do the following:

  • Dequeue the vertex with the least number of eliminations from the desired queue.

  • If the vertex is no longer visited now,

  • Mark it as visited.

  • For each adjacent vertex of the modern vertex:

  • Apply edge barriers to determine whether an edge can be considered.

  • Calculate the unused distance from the feeding vertex to the adjacent vertex taking into account edge weights and constraints.

  • Improve the delimiter array if the current delimiters are shorter than modern delimiters.

  • Queue adjacent vertices at their unused distance into the desired row.

  • After all vertices are reached, individual clusters will contain the maximum short distance from the supply vertex to each vertex that satisfies the edge constraints.

  • Return individual clusters as results.

示例

#include <iostream>
#include <vector>
#include <limits>

struct Edge {
    int destination;
    int weight;
};

void dijkstra(const std::vector<std::vector<Edge>>& graph, int source, std::vector<int>& distance) {
    int numVertices = graph.size();
    std::vector<bool> visited(numVertices, false);
    distance.resize(numVertices, std::numeric_limits<int>::max());
    distance[source] = 0;

    for (int i = 0; i < numVertices - 1; ++i) {
        int minDistance = std::numeric_limits<int>::max();
        int minVertex = -1;

        for (int v = 0; v < numVertices; ++v) {
            if (!visited[v] && distance[v] < minDistance) {
                minDistance = distance[v];
                minVertex = v;
            }
        }

        if (minVertex == -1)
            break;

        visited[minVertex] = true;

        for (const auto& edge : graph[minVertex]) {
            int destination = edge.destination;
            int weight = edge.weight;

            if (!visited[destination] && distance[minVertex] != std::numeric_limits<int>::max() &&
                distance[minVertex] + weight < distance[destination]) {
                distance[destination] = distance[minVertex] + weight;
            }
        }
    }
}

int main() {
    int numVertices = 4;
    int source = 0;
    std::vector<std::vector<Edge>> graph(numVertices);

    // Add edges to the graph (destination, weight)
    graph[0] = {{1, 10}, {2, 3}};
    graph[1] = {{2, 1}, {3, 7}};
    graph[2] = {{3, 6}};

    std::vector<int> distance;
    dijkstra(graph, source, distance);

    // Print the shortest distances from the source vertex
    std::cout << "Shortest distances from vertex " << source << ":\n";
    for (int i = 0; i < numVertices; ++i) {
        std::cout << "Vertex " << i << ": " << distance[i] << '\n';
    }

    return 0;
}
Copy after login

输出

Shortest distances from vertex 0:
Vertex 0: 0
Vertex 1: 10
Vertex 2: 3
Vertex 3: 9
Copy after login

结论

本文概述了两个重要的计算,以帮助理解协调和加权图表中的大多数问题。它阐明了易受骗的递归方法和带有边缘限制的 Dijkstra 计算。轻信递归方法包括递归地研究具有精确 k 个边的所有可能的方式,以发现最有限的方式。 Dijkstra 的边命令式计算采用了所需的线和面积规则,成功地找出了图表中从供给顶点到所有不同顶点的最大受限方式。本文包含了计算的具体说明,并给出了测试代码来说明其用法.

The above is the detailed content of In a directed weighted graph, find the shortest path containing exactly k edges.. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template