\'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
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.
Actually the [i][j] entry of A^k shows the total different "walk", not "path", in each simple graph. We can easily prove it by "mathematical induction". However, the major question is to find total different "path" in a given graph. We there are a quite bit of different algorithm to solve, but the upper band is as follow:
(n-2)(n-3)...(n-k) which "k" is the given parameter stating length of path.
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 1
s 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])
])