NxN matrix, how could I find all possible paths to a location
(i,i). Navigation would be only
downwards y hacia el
right. The starting point would be
P.S. Not a homework.
preguntado el 31 de julio de 12 a las 14:07
The easiest (for me) would be to do it recursively:
1) the stop condition would be arriving at (i,i)
2) you would try two next moves at each recursion level:
- can you go down
- can you go right
Assuming that your current position is (x,y): You cannot go right if your current "y" plus 1 would be bigger than "i" in the (i,i). You cannot go down if your current "x" plus 1 would be bigger than "i" in the (i,i).
You'd just have to remember the path in some variable or pass it downwards and print it when the stop condition occurs.
So assuming you start at (0,0) you remember this and then check if you can go right or down, if yes for both then you recursively call this same method for (0,1) and (1,0).
To a location (i, i), i.e. one on the diagonal, there are exactly comb(i, 2 * i) paths (number of ways to select i elements from a set of 2 * i elements), each consisting of i movements rightward and i movements downward. Enumerating them is trivial.
Although you can use DP to solve this, this is just simle math:
Tienes que hacer
2i steps, from which
i must be steps to the right. The total combinations are
C(2i,i). Ver: computing the binomial coefficients.
Solution 1 - Using dynamic programming :
Add up the solutions bottom up till (i,j) indices you want:
ans(i,i) = ans(i-1,j) + ans(i,j-1)
and use the same for position (i,i).
Solution 2 - Using simple permutation and combination
ans = (2i)!/ i!i!
(Since you have to choose any of the i steps towards the right and ji steps downwards starting from (0,0) and total are 2i steps).
It depends when you start from (0,0) or at a random location in the matrix.
If it is (0,0) ; use Depth First to go until the end of one branch then the others. Use Breadth First to iterate through all neigbouring nodes at a step. Check only down and right nodes.
If it is at a random location in the matrix, you need to trace all 4 neighbouring nodes.