迷宮裏的動態規劃應用
阿新 • • 發佈:2018-09-06
動態 ott pri ner lse 測試案例 exp 思路 gin
[LeetCode 63] Unique Paths II
題目
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 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
思路
記 nums[i][j] 表示從 (i,j) 點到達右下角的不同路徑數。那麽有如下遞歸式:
\[
nums[i][j] = \lbrace
\begin{align}
nums[i + 1][j] + num[i][j + 1] , \;(i,j) 處無障礙 \0,\;(i,j) 處有障礙
\end{align}
\]
代碼如下
class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m, n; if((m = obstacleGrid.length) < 1 || (n = obstacleGrid[0].length) < 1){ return 0; } int[][] nums = new int[m][n]; if((nums[m - 1][n - 1] = 1 - obstacleGrid[m - 1][n - 1]) == 0){ return 0; } for(int i = n - 2; i > -1; i--){ if(obstacleGrid[m - 1][i] == 1){ nums[m - 1][i] = 0; } else{ nums[m - 1][i] = nums[m - 1][i + 1]; } } for(int i = m - 2; i > -1; i--){ if(obstacleGrid[i][n - 1] == 1){ nums[i][n - 1] = 0; } else{ nums[i][n - 1] = nums[i + 1][n - 1]; } } for(int i = m - 2; i > -1; i--){ for(int j = n - 2; j > -1; j--){ if(obstacleGrid[i][j] == 1){ nums[i][j] = 0; } else{ nums[i][j] = nums[i + 1][j] + nums[i][j + 1]; } } } return nums[0][0]; } }
[LeetCode 64] Minimum Path Sum
題目
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
測試案例
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
代碼如下
class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[][] price = new int[m][n];
price[m - 1][n - 1] = grid[m - 1][n - 1];
for(int i = n -2; i > -1; i--){
price[m - 1][i] = price[m - 1][i + 1] + grid[m - 1][i];
}
for(int i = m - 2; i > -1; i--){
price[i][n - 1] = price[i + 1][n - 1] + grid[i][n - 1];
}
for(int i = m - 2; i> -1; i--){
for(int j = n -2; j > -1; j--){
price[i][j] = price[i + 1][j];
if(price[i][j] > price[i][j + 1]){
price[i][j] = price[i][j + 1];
}
price[i][j] += grid[i][j];
}
}
return price[0][0];
}
}
迷宮裏的動態規劃應用