EP44-UniquePathsII

Yesterday we managed to crack the UniquePaths issue via Dynamic Programming, that's a rather typical implementation of DP. Today I worked on another similar problem, which just added a little restriction on the UniquePath issue.

Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.
Note: m and n will be at most 100.

Actually it's pretty easy to come up with the state transfer equation because it's just similar as yesterday's issue, the idea is easy, just add another restriction would be okay:

 Paths[i][j] = Paths[i-1][j] + Paths[i][j-1] , array[i][j] = 1;
             = 0 , array[i][j] = 0;

However, I almost submitted for about 15 times before my code was totally accepted, barely gave up.
Compare with UniquePaths, many special condition should be considered,e.g.

  • if(obstacleGrid[0][0]==1), just return 0 would be enough ;
  • as soon as you find the 1st "1" in the first row/column, put the whole row/column into 0 and return. Because all the numbers after them would be blocked by that single grid.(Imagine:{{0, 0,}, {1, 1}, {0, 0}}).

This is the code. I remained using 2-dimension DP because of low understanding cost.

    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        if (obstacleGrid[0][0] == 1) return 0;
        for (int i = 0; i < m; i++) {
            if (obstacleGrid[i][0] == 1) {
                while (i < m) {
                    obstacleGrid[i][0] = 0;
                    i++;
                }
            } else
                obstacleGrid[i][0] = 1;
        }
        for (int j = 1; j < n; j++) {
            if (obstacleGrid[0][j] == 1) while (j < n) {
                obstacleGrid[0][j] = 0;
                j++;
            }
            else
                obstacleGrid[0][j] = 1;
        }
        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++) {
                if (obstacleGrid[i][j] == 1) {
                    obstacleGrid[i][j] = 0;
                } else if (i > 0 && j > 0) {
                    obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
                }
            }
        return obstacleGrid[m - 1][n - 1];
    }

-Jan 23

你可能感兴趣的:(EP44-UniquePathsII)