Friday, January 16, 2015

Java Code to find all paths in a grid from start to end.

/*

 1  2 3  4
 5  6   7  8
 9 10 11 12
 13 14  15  16

TC1: invalid grid.
TC2: smaller than len-1 x len-1.
TC3: Functional
           all possible routes.

Returns: number of possible routes from (0,0) to (len-1,len-1) if success,
         -1 on failure.
*/

public int numberOfPossibleRoutes(int[][] grid, int currentRow, int currentColumn, int length)
{
    if( grid  == null )
    {
        return -1;
    }
   
    if( currentRow == length-1 && currentColumn == length-1)
    {
        return 1;
    }
   
    int countToReturn=0;
    // Count the number downwards.
    if( currentRow < length - 1)
    {
        countToReturn += numberOfPossibleRoutes(grid, currentRow+1, currentColumn, length);  
    }
    else if( currentRow == length - 1)
    {
        // Only right count.
        return numberOfPossibleRoutes(grid, currentRow, currentColumn+1, length);
    }
    else
    {
        throw new ArrayIndexOutOfBoundsException();
    }
   
    // Count right possibilities
    if( currentColumn < length-1)
    {
        countToReturn += numberOfPossibleRoutes(grid, currentRow, currentColumn+1, length);   
    }
    else if( currentColumn == length-1)
    {
        return numberOfPossibleRoutes(grid, currentRow+1, currentColumn, length);
    }
    else
    {
        throw new ArrayIndexOutOfBoundsException();
    }
    
    return countToReturn;
}

No comments:

Post a Comment