Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of paths in a matrix

A p x q size matrix is given, and a matrix of size a x b is removed from top right corner. Find the total no. of paths from top left to bottom right, with only right and down movements allowed. No path should go into the removed matrix.

eg-

 _
|_|_
|_|_|

this is (2x2) matrix after removing (1x1) matrix from top right corner. no. of ways - 5.

I am able to find out the total number of paths, but the method I am thinking of eliminating the paths that go into the removed portion is very elementary and hence not efficient.

So, are there any better algorithm for it ?

like image 556
aclap Avatar asked Dec 06 '12 13:12

aclap


People also ask

How do you find the number of paths in a matrix?

The problem is to count all the possible paths from top left to bottom right of an m*n matrix with the constraints that from each cell you can either move only towards right or down. Now for the last solution, the combination formula for computing number of paths is given as m+n–2Cm–1.

How many paths does a 3x3 grid have?

For a 3x3 grid I need to make 4 moves. There are 16 possible paths. For a 4x4 grid I need to make 6 moves. There are 64 possible paths.

How many paths can A to B have?

use the multinomial rule, the possible number of paths from A to B is m! n1! ×n2!

How many ways can you traverse a matrix?

Two common ways of traversing a matrix are row-major-order and column-major-order.


1 Answers

You can exploit the structure of the grid:

The number of paths from one corner to the other on a square grid is given by the size of the grid by the pascal's triangle: (x+y) choose x

Each path must cross exactly one point on each diagonal.

Take all points on the diagonal that passes through the inner corner, calculate the number of paths through each, and sum.

This leads to an O(min(p-a, q-b)) algorithm assuming constant-time arithmetic.

In your case: (two paths to the center) * (two paths from the center) + (one path through the corner) = (four paths through the center) + (one path through the corner) = (five paths)

+-+-+
| | |
+-+-A-+-+
| | | | |
+-B-+-+-+
| | | | |
C-+-+-+-+
| | | | |
+-+-+-+-+

  (1+2) choose 1 * (2+3) choose 2 (through A)
+ (2+1) choose 2 * (3+2) choose 3 (through B)
+ (3+0) choose 3 * (4+1) choose 4 (through C)

= 3 choose 1 * 5 choose 2
+ 3 choose 2 * 5 choose 3
+ 3 choose 3 * 5 choose 4

= 3*10
+ 3*10
+ 1*5

= 30+30+5 = 65 paths
like image 187
John Dvorak Avatar answered Oct 04 '22 11:10

John Dvorak