【LeetCode-面試演算法經典-Java實現】【063-Unique Paths II(唯一路徑問題II)】,leetcode--java
【063-Unique Paths II(唯一路徑問題II)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】原題
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.
題目大意
唯一路徑問題後續,如果路徑中有障礙,求總的路徑的種數。【唯一路徑問題】
注意:網格的行數和列數都不超過100
解題思路
採用分治求解方法
用一個m*n的組數A儲存結果。
對於A數組中的元素有。
1、當x=0或者y=0時,並且(x, y)位置無障礙。有A[x][y] = 1; 有障礙就是0
2、當x>=1並且y>=1時,並且(x, y)位置無障礙。有A[x][y] = A[x-1][y]+A[x][y-1]。 有障礙就是0
3、所求的結點就是A[m-1][n-1]。
代碼實現
演算法實作類別
public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { // 輸入校正 if (obstacleGrid == null || obstacleGrid.length < 1 || obstacleGrid[0].length < 1 || obstacleGrid[0][0] == 1 || obstacleGrid[obstacleGrid.length - 1][obstacleGrid[0].length - 1] == 1) { return 0; } int rows = obstacleGrid.length; int cols = obstacleGrid[0].length; int[][] result = new int[rows][cols]; // 第一個位置有多少種方法,無障礙就是1種,有障礙就是0種 result[0][0] = obstacleGrid[0][0] == 0 ? 1 : 0; for (int i = 1; i < cols; i++) { result[0][i] = obstacleGrid[0][i] == 0 ? result[0][i - 1] : 0; } for (int i = 1; i < rows; i++) { result[i][0] = obstacleGrid[i][0] == 0 ? result[i - 1][0] : 0; } for (int i = 1; i < rows; i++) { for (int j = 1; j < cols; j++) { result[i][j] = obstacleGrid[i][j] == 0 ? result[i - 1][j] + result[i][j - 1] : 0; } } return result[rows - 1][cols - 1]; } // 使用遞迴方法會逾時 public int uniquePathsWithObstacles2(int[][] obstacleGrid) { // 輸入校正 if (obstacleGrid == null || obstacleGrid.length < 1 || obstacleGrid[0].length < 1 || obstacleGrid[obstacleGrid.length - 1][obstacleGrid[0].length - 1] == 1) { return 0; } int[] result = {0}; solve(obstacleGrid, 0, 0, result); return result[0]; } public void solve(int[][] grid, int row, int col, int[] sum) { // 到達終點 if (row == grid.length - 1 && col == grid[0].length - 1) { sum[0]++; } // 沒有到終點,點在棋盤內,並且當前位置不是 else if (row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == 0) { // 往右走 solve(grid, row, col + 1, sum); // 往下走 solve(grid, row + 1, col, sum); } }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明
歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47182723】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。