日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[LeetCode]--63. Unique Paths II

發(fā)布時(shí)間:2025/3/20 编程问答 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [LeetCode]--63. Unique Paths II 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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.

尋求最短路徑,從左上走到右下,保證每次只能往左走或往下走(不可以斜著走)。其中數(shù)字1是障礙,表示“此路不通”,求總共的路線數(shù)。

第一種二維數(shù)組

用一個(gè)二維數(shù)組來表示前者的路徑
核心就是這個(gè),如果不等于1,我們就找到前者的路徑相加。

if (obstacleGrid[i][j] == 1) { continue; } else { int tmp = obstacleGrid[i - 1][j] == 1 ? 0 : val[i - 1][j]; tmp = obstacleGrid[i][j - 1] == 1 ? tmp : tmp + val[i][j - 1]; val[i][j] = tmp; } public int uniquePathsWithObstacles1(int[][] obstacleGrid) {if (obstacleGrid[0][0] == 1)return 0;int m = obstacleGrid.length;int n = obstacleGrid[0].length;int[][] val = new int[m][n];val[0][0] = 1;for (int i = 1; i < m; i++)if (obstacleGrid[i][0] != 1 && val[i - 1][0] != 0)val[i][0] = 1;for (int i = 1; i < n; i++)if (obstacleGrid[0][i] != 1 && val[0][i - 1] != 0)val[0][i] = 1;for (int i = 1; i < m; i++) {for (int j = 1; j < n; j++) {if (obstacleGrid[i][j] == 1) {continue;} else {int tmp = obstacleGrid[i - 1][j] == 1 ? 0 : val[i - 1][j];tmp = obstacleGrid[i][j - 1] == 1 ? tmp : tmp+ val[i][j - 1];val[i][j] = tmp;}}}return val[m - 1][n - 1];}

第二種一維數(shù)組

其實(shí)一維數(shù)組足以表示前者的路徑,因?yàn)橐痪S數(shù)組左邊是你更新過的,右邊是沒更新,沒更新的相當(dāng)于上一排,也就是上一排的來路加上左邊的來路之和就是現(xiàn)在的來路。(解釋好混亂,但我是這樣想就理解了)

public int uniquePathsWithObstacles(int[][] obstacleGrid) {if (obstacleGrid[0][0] == 1)return 0;int m = obstacleGrid.length;int n = obstacleGrid[0].length;int[] step = new int[n];step[0] = 1;for (int i = 0; i < m; i++)for (int j = 0; j < n; j++) {if (obstacleGrid[i][j] == 1)step[j] = 0;else if (j > 0)step[j] += step[j - 1];}return step[n - 1];} 與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖

總結(jié)

以上是生活随笔為你收集整理的[LeetCode]--63. Unique Paths II的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。