If the matrix is square (N x N
), I believe the number of paths can be calculated as follows where n = N - 1
:
from math import factorial
def number_of_paths(n):
return int(factorial(2 * n) / (factorial(n) ** 2))
As for why... that's a little more complicated. First of all instead of thinking about going down and right, lets turn the matrix 45 degrees so that we are always going down, but choosing left or right.
Our matrix is now a diamond standing on it's end and forms the center of Pascal's triangle. This means we can look at the binomial coefficient at the center of the bottom row of Pascal's triangle which is twice the size of our matrix - 1.
We use the binomial coefficient because one interpretation of this is it shows the number of paths we can choose to get there.
For example in the 3 x 3
case, 2 * 3 - 1 = 5
:
[1] C(0,0)
[1 1] C(1,0), C(1,1)
[1 2 1] C(2,0), C(2,1), C(2,2)
1 [3 3] 1 C(3,0), C(3,1), C(3,1), C(3,1)
1 4 [!6!] 4 1 C(4,0), C(4,1), C(4,2), C(4,3), C(4,4)
Answer is 6! Answer is C(4, 2)!
The answer turns out to be (2n)! / n! ** 2
(derivation below) which we can calculate directly.
You can also generalise to non-square matrices by moving about the item in the bottom row you care about, at which point you basically just end up with C(n, k)
. Hopefully it's clear why.
Just the maths!
We can see from the diagram above that the first three values for N are:
N | Value
- + -------
1 | C(0, 0)
2 | C(2, 1)
3 | C(4, 2)
We can therefore see that the answer is:
= C(2(N - 1), N - 1)
let n = N-1
Given C(a, b) = a! / b!(a - b)!
= C(2n, n)
= (2n)! / n!(2n - n)!
= (2n)! / n! ** 2
A geometric interpretation of path length
Imagine the case of a 4x4
matrix to try and see why the length is 2(N-1)
. First a few observations:
- All path lengths are identical
- We can therefore consider any particular path to examine the length for all
- Therefore lets consider the path from:
- Top left to top right (all going right)
- Then top right to bottom right (all down)
To begin we start at the top left with no moves having been made, and progress along the top side:
0 - - - 0 1 - - 0 1 2 - 0 1 2 3
- - - - > - - - - > - - - - > - - - -
- - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - -
After 3 moves we have traversed the length 4 side. So for a side of length N
it takes N-1
moves to traverse. The same is true for the vertical, it will take us another N-1
moves to traverse from the top to the bottom:
0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3
- - - - > - - - 4 > - - - 4 > - - - 4
- - - - - - - - - - - 5 - - - 5
- - - - - - - - - - - - - - - 6
Therefore the total path length is 2(N-1)