63. 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.
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 is2.
Note: m and n will be at most 100.

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length,n = obstacleGrid[0].length;
        int[][] f = new int[m][n];
        f[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1;
        for(int i=1;i<m;i++)
           f[i][0] = obstacleGrid[i][0] == 1 ? 0 : f[i-1][0];
        for(int j=1;j<n;j++)
           f[0][j] = obstacleGrid[0][j] == 1 ? 0 : f[0][j-1];
        for(int i=1;i<m;i++)
          for(int j=1;j<n;j++)
          f[i][j] = obstacleGrid[i][j] == 1 ? 0 : f[i-1][j] + f[i][j-1];
        return f[m-1][n-1];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 春季 虽有各路花色 但 终究逃不过对尘土的依恋 跳动的雨水夹杂着泥土的腥气 秒秒中袭来 拼命的驱散着前行的脚步 被...
    Smile娜娜阅读 174评论 0 0
  • spring提供注解@SessionAttributes将Model中的数据同步到HttpSession中。在清除...
    dierrenjian阅读 1,143评论 0 2
  • 当被群主告知今天(12月25日)也是希坦博士的生日,中午将有一群来自五湖四海,天南海北的陌生而又亲密的朋友们将聚...
    怡然庄主阅读 837评论 0 1
  • 今天等203路车,等啊,等啊…46路车在眼前停了一下,好像这车也到啊,刚到车门前却犹豫了一下,在犹豫间车开走...
    飞翔的樱花阅读 213评论 0 1