LeetCode Unique Paths II
来源:互联网 发布:淘宝量身定做羊绒衫 编辑:程序博客网 时间:2024/06/05 01:34
Description:
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.
Solution:
这道题目和Unique Paths本质上是一样的,只是多了一个额外的限制条件,obstacleGrid数组的限制,那么只要我在初始化和状态表示的时候进行相应的对-1的特判即可。
1.先把所有在obstacleGrid中表示无法通行的点在dp[i][j]中用-1表示
2.初始化中,dp[0][0]如果为-1则返回0;否则为1。然后对于第0行,每一个dp[0][i]如果不为-1,则与前一个dp[0][i-1]相同,同为0或者同为1。第0列也类似。
3.在后续状态变化的过程中,状态的变化方程和前面一样,也是dp[i][j] = dp[i-1][j] + dp[i][j-1],只不过多了个限制条件,就是只有在dp[i][j-1] != -1的情况下可以加dp[i][j-1],在dp[i-1][j] != -1的情况下可以加dp[i-1][j]。
注意:这里的初始化需要多考虑考虑。
import java.util.*;public class Solution {public int uniquePathsWithObstacles(int[][] obstacleGrid) {int m = obstacleGrid.length;int n = obstacleGrid[0].length;int dp[][] = new int[m][n];if (obstacleGrid[0][0] == 1)return 0;elsedp[0][0] = 1;for (int i = 0; i < m; i++)for (int j = 0; j < n; j++)if (obstacleGrid[i][j] == 1)dp[i][j] = -1;for (int i = 1; i < m; i++)if (dp[i][0] != -1) {if (dp[i - 1][0] != -1)dp[i][0] = dp[i - 1][0];}for (int i = 1; i < n; i++)if (dp[0][i] != -1) {if (dp[0][i - 1] != -1)dp[0][i] = dp[0][i - 1];}for (int i = 1; i < m; i++)for (int j = 1; j < n; j++)if (dp[i][j] == 0) {if (dp[i][j - 1] >= 0)dp[i][j] += dp[i][j - 1];if (dp[i - 1][j] >= 0)dp[i][j] += dp[i - 1][j];}if (dp[m - 1][n - 1] == -1)return 0;return dp[m - 1][n - 1];}}
0 0
- LeetCode: Unique Paths II
- [Leetcode] Unique Paths II
- LeetCode : Unique Paths II
- [LeetCode] Unique Paths II
- [LeetCode]Unique Paths II
- [leetcode]Unique Paths II
- LeetCode-Unique Paths II
- [leetcode] Unique Paths II
- LeetCode - Unique Paths II
- LeetCode:Unique Paths II
- 【LeetCode】Unique Paths II
- leetcode Unique Paths II
- LeetCode Unique Paths II
- LeetCode | Unique Paths II
- Leetcode: Unique Paths II
- LeetCode Unique Paths II
- Unique Paths II -- LeetCode
- [LeetCode] Unique Paths II
- 直接拿来用!十大Material Design开源项目
- 阿里巴巴实习生负一天
- 开始写技(xue)术(xi)博(bi)客(ji)
- 题目1153:括号匹配问题
- How to make a sprite from URL in cocos2d-x
- LeetCode Unique Paths II
- Maven的pom.xml介绍
- Maven简介(六)——Dependency
- STC不断电下载
- 黑马程序员-OC语言-创建一个对象并访问成员变量(听课笔记)
- Maven简介(二)——使用Maven
- github android 项目地址
- 详解android:scaleType属性
- ViewPager(1)