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

2147483647 picture 2147483647 · Jan 11, 2013 · Viewed 20.4k times · Source

'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 source vertex to the destination vertex of given length k.

  • We can visit each vertex as many times as we want, so if a path from a to b goes like this: a -> c -> b -> c -> b it is considered valid. This means there can be cycles and we can go through the destination more than once.

  • Two vertices can be connected by more than one edge. So if vertex a an vertex b are connected by two edges, then the paths , a -> b via edge 1 and a -> b via edge 2 are considered different.

  • Number of vertices N is <= 70, and K, the length of the path, is <= 10^9.

  • As the answer can be very large, it is to be reported modulo some number.

Here is what I have thought so far:

We can use breadth-first-search without marking any vertices as visited, at each iteration, we keep track of the number of edges 'n_e' we required for that path and product 'p' of the number of duplicate edges each edge in our path has.

The search search should terminate if the n_e is greater than k, if we ever reach the destination with n_eequal to k, we terminate the search and add p to out count of number of paths.

I think it we could use a depth-first-search instead of breadth first search, as we do not need the shortest path and the size of Q used in breadth first search might not be enough.

The second algorithm i have am thinking about, is something similar to Floyd Warshall's Algorithm using this approach . Only we dont need a shortest path, so i am not sure this is correct.

The problem I have with my first algorithm is that 'K' can be upto 1000000000 and that means my search will run until it has 10^9 edges and n_e the edge count will be incremented by just 1 at each level, which will be very slow, and I am not sure it will ever terminate for large inputs.

So I need a different approach to solve this problem; any help would be greatly appreciated.

Answer

Dennis Meng picture Dennis Meng · Jan 11, 2013

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.