• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

LeetCodeOnlineJudge题目C#练习-UniquePathsII

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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.

 1         public static int UniquePathsIIDP(List<List<int>> obstacleGrid)
 2         {
 3             int m = obstacleGrid.Count;
 4             int n = obstacleGrid[0].Count;
 5             int[,] grid = new int[m, n];
 6 
 7             // if the start point is a obstacle, return 0
 8             if (obstacleGrid[0][0] == 1)
 9                 return 0;
10             grid[0, 0] = 1;
11 
12             for (int i = 1; i < m; i++)
13             {
14                 if (obstacleGrid[i][0] == 0 && grid[i - 1, 0] != 0)
15                     grid[i, 0] = 1;
16                 else
17                     grid[i, 0] = 0;
18             }
19 
20             for (int i = 1; i < n; i++)
21             {
22                 if (obstacleGrid[0][i] == 0 && grid[0, i - 1] != 0)
23                     grid[0, i] = 1;
24                 else
25                     grid[0, i] = 0;
26             }
27 
28             for (int i = 1; i < m; i++)
29             {
30                 for (int j = 1; j < n; j++)
31                 {
32                     if (obstacleGrid[i][j] == 1)
33                         grid[i, j] = 0;
34                     else
35                         grid[i, j] = grid[i - 1, j] + grid[i, j - 1];
36                 }
37             }
38 
39             return grid[m - 1, n - 1];
40         }

代码分析:

  这题用DP,超容易。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
深入理解C#静态类与非静态类、静态成员的区别发布时间:2022-07-10
下一篇:
C# 删除某一个目录中所有的txt文件发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap