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

后端 未结 3 545
醉梦人生
醉梦人生 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:10

    So, here's a nifty graph theory trick that I remember for this one.

    Make an adjacency matrix A. where A[i][j] is 1 if there is an edge between i and j, and 0 otherwise.

    Then, the number of paths of length k between i and j is just the [i][j] entry of A^k.

    So, to solve the problem, build A and construct A^k using matrix multiplication (the usual trick for doing exponentiation applies here). Then just look up the necessary entry.

    EDIT: Well, you need to do the modular arithmetic inside the matrix multiplication to avoid overflow issues, but that's a much smaller detail.

提交回复
热议问题