Saturday, August 12th

 Robot paths

Given a grid with obstacles, return the number of unique paths from start to end

Image courtesy of Andrejo Linares Garcia via Wikipedia, under Creative Commons Attribution-Share Alike 3.0 Unported.  No changes made

When calculating different paths, many paths may use portions of the same path, thus this problem can be approached through dynamic programming

We will solve this dynamic programming problem from the bottom up.  Since the location of the robot is determined by the x and y coordinates, we will implement a solution with 2 state variables.

First we test if the beginning square is an obstacle, and if so, return 0, since there are no possible paths since the first square is impassable. 

    if(obstacleGrid[0][0]==1) return 0;

Otherwise we continue to solve the problem.  Using the lengths of the matrix, we create a table to hold intermediate results

    int n = obstacleGrid.size(); 
    int m = obstacleGrid[0].size(); 
    vector<vector<int> > dp(n, vector<int>(m));

Now to calculate paths.  We start by setting the obstacle-less first square to 1, since there's only 1 way to get there

        dp[0][0]=1;

Then we iterate over all the squares in the dp table

    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            ...
        }
    }

Since a robot travels only down and right, the number of paths to a given square is equal to the number of paths to the square above and to the left of it.  To calculate this we mind squares on the left and top edges

If a particular square isn't in the first row, and the same square isn't an obstacle, then the square in the next row below it has all the same number of paths to the square in the row before

    if(i>0 && obstacleGrid[i][j]!= 1) {
        dp[i][j] += dp[i-1][j]; 
    }

Similarly, if a square isn't in the first column and isn't an obstacle, the number of unique paths through the square is added by the number of nodes in the column above 
    
    if(j>0 && obstacleGrid[i][j]!= 1) {
        dp[i][j] += dp[i][j-1];
    }

After traversing the matrix top to bottom, left to right, we return the number of paths in the final square

    return dp[n-1][m-1];

Straight-forward dynamic programming problem that was included in the DP explore card.  All matrix traversal questions use a dp table of equal size.

asdf

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th