Leetcode 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 is 2.

Note: m and n will be at most 100.

 

 

 
 
 1 public class Solution {
 2     public int UniquePathsWithObstacles(int[,] obstacleGrid) {
 3         int m = obstacleGrid.GetLength(0), n = obstacleGrid.GetLength(1);
 4         
 5         // optimization: we can do in-place
 6         var dp = new int[m, n];
 7         
 8         for (int i = m - 1; i >= 0; i--)
 9         {
10             for (int j = n - 1; j >= 0; j--)
11             {
12                 if (i == m - 1 && j == n - 1)
13                 {
14                     if (obstacleGrid[i , j] == 1) return 0;
15                     dp[i, j] = 1;
16                 }
17                 else if (i == m - 1)
18                 {
19                     dp[i, j] = obstacleGrid[i , j] == 1 ? 0 : dp[i, j + 1];
20                 } 
21                 else if (j == n - 1)
22                 {
23                     dp[i, j] = obstacleGrid[i , j] == 1 ? 0 : dp[i + 1, j];
24                 }
25                 else
26                 {
27                     dp[i, j] = obstacleGrid[i , j] == 1 ? 0 : dp[i + 1, j] + dp[i, j + 1];
28                 }
29             }
30         }
31         
32         return dp[0, 0];
33     }
34 }

 

posted @ 2017-11-10 05:21  逸朵  阅读(125)  评论(0)    收藏  举报