Monday, January 4, 2010

Count the number of shortest path

Given a grid and two nodes (say A & B) on the grid which is h units apart horizontally and v units apart vertically, give the count of number of shortest path along the grid lines between A & B.

For example, take the case below where A & B are 1 unit apart horizontally and 1 unit apart vertically i.e. h = 1 and v = 1.
In this case, the answer is 2 as shown below:

Give your answer in terms of h and v for the generic case.



// Shortest Paths.cpp : Defines the entry point for the console application.

//

#include
#include

int h,v;
long int count=0;
int main()
{
    void path(int m,int n);
    int i,j;
    clrscr();
    printf("Enter the horizontal length: ");
    scanf("%d",&h);
    printf("Enter the vertical height: ");
    scanf("%d",&v);
    path(0,0);
    printf("The number of shortest paths is: %ld",count);
    getch();
    return 0;
}
void path(int m,int n)
{
    if(m==h || n==v)
    {
         count++;
         return;
    }
    else
    {
         path(m+1,n);
         path(m,n+1);
    }
}

Enter the horizontal length: 3
Enter the vertical height: 3
The number of shortest paths is: 20

Enter the horizontal length: 10
Enter the vertical height: 10
The number of shortest paths is: 184756

Enter the horizontal length: 2
Enter the vertical height: 1
The number of shortest paths is: 3

Enter the horizontal length: 1
Enter the vertical height: 1
The number of shortest paths is: 2

2 comments:

  1. For this problem, you could also use combinatorics! Basically, if you have a horizontal length X and vertical height Y, then the total number of steps you need to take at minimum is X+Y. Now, assume you are are walking horizontally... at every step you can choose to take your vertical step as long as in total you take Y of them (and vice-versa), so the problem reduces down to:

    Number of shortest paths = (X+Y) choose X = (X+Y) choose Y

    ReplyDelete
  2. Thanks for your suggestion. Yes you are right. I learned about this approach later.

    ReplyDelete