Amazon Interview Question
SDE-2sCountry: India
Interview Type: Written Test
No.
If you only allow down and right AND the matrix is square (n+1 by n+1), then the number of paths is (2n) choose (n).
The number of paths that cross the diagonal from (0,0) to (n+1, n+1) is (2n) choose (n+1)
So Catalan number of order n counts the number of paths from (0,0) to (n+1, n+1) that do not cross the diagonal:
C_n = (2n)choose(n) - (2n)choose(n+1)
The posted problem is different.
If only down and right are allowed the solution is simple by using combinatorics, in a [m][n] matrix the answer is C(m+n, m).
You can also use backtracking to find the paths, just keep adding one until all paths are exhausted.
If we assume the robot can only move down and to its right.
/* compute the number of move of a robot
* from (0,0) to (x,y)
*/
unsigned long long robot_table[1024][1024];
unsigned long long robot_move (int x, int y)
{
if (x == 0) {
return (1);
}
if (y == 0) {
return (1);
}
if (robot_table[x][y]) {
return (robot_table[x][y]);
}
robot_table[x][y] = robot_move(x-1, y) + robot_move(x, y-1);
return (robot_table[x][y]);
}
In this case the answer is:
(m+n-2)!/ { (m-1)!(n-1)! }
Because every path is associated with a permutation of the letters: RRRR(n-1 times)RRRDDDDD(m-1 times)DDDD
int ii = 4;
int jj = 4;
int max_path(int i, int j){
int count=0;
if(i==(ii-1) && j == (jj-1)){
return 1;
}
if(i < ii){
count += max_path(i+1,j);
}
if(j < jj){
count += max_path(i,j+1);
}
return count;
}
int _tmain(int argc, _TCHAR* argv[])
{
printf("Number of Paths: %d", max_paths(0,0));
return 0;
}
Check this
- Sai August 11, 2013techieme.in/techieme/dynamic-programming-distinct-paths-between-two-points/