LeetCode: Unique Paths II

一次过了

 1 class Solution {

 2 public:

 3     int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         int m = obstacleGrid.size();

 7         if (!m) return 0;

 8         int n = obstacleGrid[0].size();

 9         vector<vector<int>> f(m+1, vector<int>(n+1, 0));

10         f[0][1] = 1, f[1][0] = 1;

11         for (int i = 1; i <= m; i++) {

12             f[i][1] = obstacleGrid[i-1][0] == 1? 0 : f[i-1][1];

13         }

14         for (int i = 1; i <= n; i++) {

15             f[1][i] = obstacleGrid[0][i-1] == 1? 0 : f[1][i-1];

16         }

17         for (int i = 2; i <= m; i++) {

18             for (int j = 2; j <= n; j++) {

19                 f[i][j] = obstacleGrid[i-1][j-1] == 1? 0 : f[i-1][j] + f[i][j-1];

20             }

21         }

22         return f[m][n];

23     }

24 };

 C#

 1 public class Solution {

 2     public int UniquePathsWithObstacles(int[,] obstacleGrid) {

 3         int m = obstacleGrid.GetLength(0);

 4         int n = obstacleGrid.GetLength(1);

 5         if (m == 0 || n == 0) return 0;

 6         int[,] f = new int[m+1, n+1];

 7         f[0, 1] = f[1, 0] = 1;

 8         for (int i = 1; i <= m; i++) {

 9             f[i, 1] = obstacleGrid[i-1, 0] == 1? 0 : f[i-1, 1];

10         }

11         for (int i = 1; i <= n; i++) {

12             f[1, i] = obstacleGrid[0, i-1] == 1? 0 : f[1, i-1];

13         }

14         for (int i = 2; i <= m; i++) {

15             for (int j = 2; j <= n; j++) {

16                 f[i, j] = obstacleGrid[i-1, j-1] == 1? 0 : f[i-1, j] + f[i, j-1];

17             }

18         }

19         return f[m, n];

20     }

21 }
View Code

 

你可能感兴趣的:(LeetCode)