Finding the number of paths of given length in a undirected unweighted graph

后端 未结 3 531
醉梦人生
醉梦人生 2020-12-24 00:35

\'Length\' of a path is the number of edges in the path.

Given a source and a destination vertex, I want to find the number of paths form the s

3条回答
  •  独厮守ぢ
    2020-12-24 01:22

    Let me add some more content to above answers (as this is the extended problem I faced). The extended problem is

    Find the number of paths of length k in a given undirected tree.

    The solution is simple for the given adjacency matrix A of the graph G find out Ak-1 and Ak and then count number of the 1s in the elements above the diagonal (or below).

    Let me also add the python code.

    import numpy as np
    
    def count_paths(v, n, a):
        # v: number of vertices, n: expected path length
        paths = 0    
        b = np.array(a, copy=True)
    
        for i in range(n-2):
            b = np.dot(b, a)
    
        c = np.dot(b, a)
        x = c - b
    
        for i in range(v):
            for j in range(i+1, v):
                if x[i][j] == 1:
                    paths = paths + 1
    
        return paths
    
    print count_paths(5, 2, np.array([
                    np.array([0, 1, 0, 0, 0]),
                    np.array([1, 0, 1, 0, 1]),
                    np.array([0, 1, 0, 1, 0]),
                    np.array([0, 0, 1, 0, 0]),
                    np.array([0, 1, 0, 0, 0])
                ])
    

提交回复
热议问题