LeetCode(中等)不同路徑II(c#)

題目爲 一個機器人位於一個 m x n 網格的左上角 (起始點在下圖中標記爲“Start” )。
機器人每次只能向下或者向右移動一步。機器人試圖達到網格的右下角(在下圖中標記爲“Finish”)。
現在考慮網格中有障礙物。那麼從左上角到右下角將會有多少條不同的路徑?

在這裏插入圖片描述
在這裏插入圖片描述
一開始考慮的思路是按照廣度遍歷去搜索,但對於遞歸,由於數組數量的增加,遞歸佔用內存較多,所以會超時,但我覺得這也是一種思路,代碼如下

    public int UniquePathsWithObstacles(int[][] obstacleGrid) {
        treeNodeAll(obstacleGrid, 0, 0);
            return sum;
    }
    int sum = 0;
    public void treeNodeAll(int[][] obstacleGrid, int left, int right)
    {
            if (obstacleGrid.Length > left && obstacleGrid[left].Length > right && obstacleGrid[left][right] == 0)
            {
                treeNodeAll(obstacleGrid, left + 1, right);
                treeNodeAll(obstacleGrid, left, right + 1);
                if (left == obstacleGrid.Length - 1 && right == obstacleGrid[left].Length - 1)
                {
                    sum++;
                }
            }
            else
            {
                
            }
    }

看了官方題解,使用了動態規劃,思路就是,任意位置的路徑值就是這個點對應的左側節點或者上側節點的路線總數和。有了這個思路,代碼很容易寫出來,新建數組,我們先給最左側一列和最上方一行按照該路徑是否通暢賦值。之後遍歷數組,代碼如下

		public int UniquePathsWithObstacles(int[][] obstacleGrid)
        {
            int width = obstacleGrid[0].Count();
            int height = obstacleGrid.Length;
            if (width<1||height<1)
            {
                return 0;
            }
            int[][] newRes = new int[height][];
            for (int i = 0; i < height; i++)
            {
                newRes[i] = new int[width];
            }
            int w1 = 0, h1 = 0;
            while (w1<width)
            {
                if (obstacleGrid[0][w1]==1)
                {
                    break;
                }
                newRes[0][w1] = 1;
                w1++;
            }
            while (h1 < height)
            {
                if (obstacleGrid[h1][0] == 1)
                {
                    break;
                }
                newRes[h1][0] = 1;
                h1++;
            }
            for (int i = 1; i < height; i++)
            {
                for (int j = 1; j < width; j++)
                {
                    if (obstacleGrid[i][j]==0)
                    {
                        newRes[i][j] = newRes[i - 1][j] + newRes[i][j - 1];
                    }
                }
            }
            return newRes[height - 1][width-1];
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章