📌  相关文章
📜  计算两个顶点之间的所有可能路径

📅  最后修改于: 2021-05-05 03:05:47             🧑  作者: Mango

计算有向图中两个顶点之间存在的路径或路径的总数。这些路径不包含循环,足够简单的原因是循环包含无限数量的路径,因此会产生问题。
例子:

For the following Graph:

Input: Count paths between A and E
Output : Total paths between A and E are 4
Explanation: The 4 paths between A and E are:
                      A -> E
                      A -> B -> E
                      A -> C -> E
                      A -> B -> D -> C -> E 

Input : Count paths between A and C
Output : Total paths between A and C are 2
Explanation: The 2 paths between A and C are:
                      A -> C
                      A -> B -> D -> C

方法:
该问题可以使用回溯来解决,即走一条路径并开始在其上行走,并检查是否将我们引向目标顶点,然后计算路径并回溯以走另一条路径。如果路径没有通向目标顶点,则丢弃该路径。
这种图形遍历称为回溯。
上图的回溯可以显示为:
红色顶点为源顶点,浅蓝色顶点为目标顶点,其余为中间路径或废弃路径。

这给出了源(A)目标(E)顶点之间的四个路径。
为什么此解决方案不适用于包含循环的图形?
与此相关的问题是,如果现在在C和B之间再增加一个边,它将形成一个循环(B-> D-> C-> B) 。因此,在循环的每个循环之后,长度路径将增加,这将被视为不同的路径,并且由于循环的原因,将有无限多的路径。

算法:

  1. 创建一个采用图节点索引和目标索引的递归函数。保留全局或静态变量计数以存储计数。
  2. 如果当前节点是目的地,则增加计数。
  3. 对于所有相邻节点(即,可从当前节点访问的节点),则使用相邻节点和目标的索引来调用递归函数。
  4. 打印计数。

执行:

C++
/*
 * C++ program to count all paths from a source to a
 * destination.
 * https://www.geeksforgeeks.org/count-possible-paths-two-vertices/
 * Note that the original example has been refactored.
 */
#include 
#include 
using namespace std;
 
/*
 * A directed graph using adjacency list representation;
 * every vertex holds a list of all neighbouring vertices
 * that can be reached from it.
 */
class Graph {
public:
    // Construct the graph given the number of vertices...
    Graph(int vertices);
    // Specify an edge between two vertices
    void add_edge(int src, int dst);
    // Call the recursive helper function to count all the
    // paths
    int count_paths(int src, int dst);
 
private:
    int m_vertices;
    list* m_neighbours;
    void path_counter(int src, int dst, int& path_count);
};
 
Graph::Graph(int vertices)
{
    m_vertices = vertices; // unused!!
    /* An array of linked lists - each element corresponds
    to a vertex and will hold a list of neighbours...*/
    m_neighbours = new list[vertices];
}
 
void Graph::add_edge(int src, int dst)
{
    m_neighbours[src].push_back(dst);
}
 
int Graph::count_paths(int src, int dst)
{
    int path_count = 0;
    path_counter(src, dst, path_count);
    return path_count;
}
 
/*
 * A recursive function that counts all paths from src to
 * dst. Keep track of the count in the parameter.
 */
void Graph::path_counter(int src, int dst, int& path_count)
{
    // If we've reached the destination, then increment
    // count...
    if (src == dst) {
        path_count++;
    }
    // ...otherwise recurse into all neighbours...
    else {
        for (auto neighbour : m_neighbours[src]) {
            path_counter(neighbour, dst, path_count);
        }
    }
}
 
// Tests...
int main()
{
    // Create a graph given in the above diagram - see link
    Graph g(5);
    g.add_edge(0, 1);
    g.add_edge(0, 2);
    g.add_edge(0, 3);
    g.add_edge(1, 3);
    g.add_edge(1, 4);
    g.add_edge(2, 3);
    g.add_edge(2, 4);
    // Validate it...
    assert(3 == g.count_paths(0, 3));
 
    return 0;
}


Java
// Java program to count all paths from a source
// to a destination.
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
 
// This class represents a directed graph using
// adjacency list representation
 
class Graph {
 
    // No. of vertices
    private int V;
 
    // Array of lists for
    // Adjacency List
    // Representation
    private LinkedList adj[];
 
    @SuppressWarnings("unchecked")
    Graph(int v)
    {
        V = v;
        adj = new LinkedList[v];
        for (int i = 0; i < v; ++i)
            adj[i] = new LinkedList<>();
    }
 
    // Method to add an edge into the graph
    void addEdge(int v, int w)
    {
 
        // Add w to v's list.
        adj[v].add(w);
    }
 
    // A recursive method to count
    // all paths from 'u' to 'd'.
    int countPathsUtil(int u, int d,
                       int pathCount)
    {
 
        // If current vertex is same as
        // destination, then increment count
        if (u == d) {
            pathCount++;
        }
 
        // Recur for all the vertices
        // adjacent to this vertex
        else {
            Iterator i = adj[u].listIterator();
            while (i.hasNext()) {
                int n = i.next();
                pathCount = countPathsUtil(n, d, pathCount);
            }
        }
        return pathCount;
    }
 
    // Returns count of
    // paths from 's' to 'd'
    int countPaths(int s, int d)
    {
 
        // Call the recursive method
        // to count all paths
        int pathCount = 0;
        pathCount = countPathsUtil(s, d,
                                   pathCount);
        return pathCount;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        Graph g = new Graph(5);
        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(0, 3);
        g.addEdge(1, 3);
        g.addEdge(2, 3);
        g.addEdge(1, 4);
        g.addEdge(2, 4);
 
        int s = 0, d = 3;
        System.out.println(g.countPaths(s, d));
    }
}
 
// This code is contributed by shubhamjd.


Python3
# Python 3 program to count all paths
# from a source to a destination.
 
# A directed graph using adjacency
# list representation
class Graph:
 
    def __init__(self, V):
        self.V = V
        self.adj = [[] for i in range(V)]
     
    def addEdge(self, u, v):
         
        # Add v to u’s list.
        self.adj[u].append(v)
     
    # Returns count of paths from 's' to 'd'
    def countPaths(self, s, d):
         
        # Mark all the vertices
        # as not visited
        visited = [False] * self.V
     
        # Call the recursive helper
        # function to print all paths
        pathCount = [0]
        self.countPathsUtil(s, d, visited, pathCount)
        return pathCount[0]
     
    # A recursive function to print all paths
    # from 'u' to 'd'. visited[] keeps track 
    # of vertices in current path. path[]
    # stores actual vertices and path_index
    # is current index in path[]
    def countPathsUtil(self, u, d,
                       visited, pathCount):
        visited[u] = True
     
        # If current vertex is same as
        # destination, then increment count
        if (u == d):
            pathCount[0] += 1
     
        # If current vertex is not destination
        else:
             
            # Recur for all the vertices
            # adjacent to current vertex
            i = 0
            while i < len(self.adj[u]):
                if (not visited[self.adj[u][i]]):
                    self.countPathsUtil(self.adj[u][i], d,
                                        visited, pathCount)
                i += 1
     
        visited[u] = False
 
# Driver Code
if __name__ == '__main__':
 
    # Create a graph given in the
    # above diagram
    g = Graph(4)
    g.addEdge(0, 1)
    g.addEdge(0, 2)
    g.addEdge(0, 3)
    g.addEdge(2, 0)
    g.addEdge(2, 1)
    g.addEdge(1, 3)
 
    s = 2
    d = 3
    print(g.countPaths(s, d))
 
# This code is contributed by PranchalK


C#
// C# program to count all paths from a source
// to a destination.
using System;
using System.Collections.Generic;
 
// This class represents a directed graph using
// adjacency list representation
public class Graph {
 
    // No. of vertices
    int V;
 
    // Array of lists for
    // Adjacency List
    // Representation
    private List[] adj;
 
    Graph(int v)
    {
        V = v;
        adj = new List[v];
        for (int i = 0; i < v; ++i)
            adj[i] = new List();
    }
 
    // Method to add an edge into the graph
    void addEdge(int v, int w)
    {
 
        // Add w to v's list.
        adj[v].Add(w);
    }
 
    // A recursive method to count
    // all paths from 'u' to 'd'.
    int countPathsUtil(int u, int d,
                       int pathCount)
    {
 
        // If current vertex is same as
        // destination, then increment count
        if (u == d) {
            pathCount++;
        }
 
        // Recur for all the vertices
        // adjacent to this vertex
        else {
            foreach(int i in adj[u])
            {
                int n = i;
                pathCount = countPathsUtil(n, d,
                                           pathCount);
            }
        }
        return pathCount;
    }
 
    // Returns count of
    // paths from 's' to 'd'
    int countPaths(int s, int d)
    {
 
        // Call the recursive method
        // to count all paths
        int pathCount = 0;
        pathCount = countPathsUtil(s, d,
                                   pathCount);
        return pathCount;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        Graph g = new Graph(5);
        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(0, 3);
        g.addEdge(1, 3);
        g.addEdge(2, 3);
        g.addEdge(1, 4);
        g.addEdge(2, 4);
 
        int s = 0, d = 3;
        Console.WriteLine(g.countPaths(s, d));
    }
}
 
// This code is contributed by Rajput-Ji


输出:

3

复杂度分析:

  • 时间复杂度: O(N!)。
    如果该图完整,则大约为N!递归调用,因此时间复杂度为O(N!)
  • 空间复杂度: O(1)。
    由于不需要额外的空间。