C#LeetCode刷题之#63-不同路径 II​​​​​​​(Unique Paths II)

C#LeetCode刷题之#63-不同路径 II​​​​​​​(Unique Paths II)

目录

问题

一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。

机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。

现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?

在这里插入图片描述

网格中的障碍物和空位置分别用 1 和 0 来表示。

说明:m 和 n 的值均不超过 100。

输入: [
[0,0,0],
[0,1,0],
[0,0,0]
]

输出: 2

解释: 3×3 网格的正中间有一个障碍物。从左上角到右下角一共有 2 条不同的路径:

  1. 向右 -> 向右 -> 向下 -> 向下
  2. 向下 -> 向下 -> 向右 -> 向右

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

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.

Note: m and n will be at most 100.

Input: [
[0,0,0],
[0,1,0],
[0,0,0]
]

Output: 2 Explanation:

There is one obstacle in the middle of the 3×3 grid above. There are two ways to reach the bottom-right corner:

  1. Right -> Right -> Down -> Down
  2. Down -> Down -> Right -> Right

示例

public class Program {

    public static void Main(string[] args) {
        var obstacleGrid = new int[,] {
            { 0, 0, 0 },
            { 0, 1, 0 },
            { 0, 0, 0 }
        };

        var res = UniquePathsWithObstacles(obstacleGrid);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static int UniquePathsWithObstacles(int[,] obstacleGrid) {
        var m = obstacleGrid.GetLength(0);
        var n = obstacleGrid.GetLength(1);

        if(m == 0 || n == 0) return 0;
        var dp = new int[m, n];

        for(var i = 0; i < m; i++) {
            for(var j = 0; j < n; j++) {
                if(obstacleGrid[i, j] == 0) {
                    if(i == 0 && j == 0) dp[i, j] = 1;
                    else if(i == 0) dp[i, j] = dp[i, j - 1];
                    else if(j == 0) dp[i, j] = dp[i - 1, j];
                    else dp[i, j] = dp[i, j - 1] + dp[i - 1, j];
                }
            }
        }
        return dp[m - 1, n - 1];
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

2

分析

显而易见, 以上算法的时间复杂度为:O(m*n)O(mn) 。

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。

转载请注明本文地址:https://www.byteflying.com/archives/3682

发表评论

登录后才能评论