LeetCode Online Judge 题目C# 练习 - 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 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,超容易。

你可能感兴趣的:(LeetCode)