Unique Paths II

Unique Paths II

问题:

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.

思路:

  简单的动态规划

我的代码:

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) return 0;
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        if(obstacleGrid[0][0] == 1)
            obstacleGrid[0][0] = 0;
        else
            obstacleGrid[0][0] = 1;
        for(int k = 1; k < m; k++)
        {
            if(obstacleGrid[k][0] != 1)
                obstacleGrid[k][0] = obstacleGrid[k-1][0];
            else
                obstacleGrid[k][0] = 0;
        }
        for(int k = 1; k < n; k++)
        {
            if(obstacleGrid[0][k] != 1)
                obstacleGrid[0][k] = obstacleGrid[0][k-1];
            else
                obstacleGrid[0][k] = 0;
        }
        for(int i = 1; i < m; i++)
        {
            for(int j = 1; j < n; j++)
            {
                if(obstacleGrid[i][j] == 1)
                {
                    obstacleGrid[i][j] = 0;
                }
                else
                {
                    obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1];
                }
            }
        }
        return obstacleGrid[m-1][n-1];
    }
}
View Code

别人代码:

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) {
            return 0;
        }
        
        int n = obstacleGrid.length;
        int m = obstacleGrid[0].length;
        int[][] paths = new int[n][m];
        
        for (int i = 0; i < n; i++) {
            if (obstacleGrid[i][0] != 1) {
                paths[i][0] = 1;
            } else {
                break;
            }
        }
        
        for (int i = 0; i < m; i++) {
            if (obstacleGrid[0][i] != 1) {
                paths[0][i] = 1; 
            } else {
                break;
            }
        }
        
        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                if (obstacleGrid[i][j] != 1) {
                    paths[i][j] = paths[i - 1][j] + paths[i][j - 1];
                } else {
                    paths[i][j] = 0;
                }
            }
        }
        
        return paths[n - 1][m - 1];
    }
}
View Code

学习之处:

  • 对于第一行的corner case 需要考虑的较多,所以AC了几次还是没过去,看别人代码里面 对于第一行或者第一列中那个break用的真是恰到好处,节约了时间,解决了corner case,学习一下

posted on 2015-03-12 16:52  zhouzhou0615  阅读(126)  评论(0编辑  收藏  举报

导航