Title:
Follow up for "Unique Paths":
Now consider if some obstacles is added to the grids. How many unique paths would there be?
An obstacle and empty space are marked as and respectively in the 1 0 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 would be is at most 100.
Test Instructions:
followed by the topic "Unique Paths", now gives the topic:
If you add some obstacles to the lattice, how many existing and unique paths will appear?
Barriers and blank squares are labeled and 1 0 .
For example , there is a barrier in the middle of a 3x3 lattice, as shown below:
[ [0,0,0], [0,1,0], [0,0,0]
The total number of paths is 2.
Algorithm Analysis:
The idea is similar to the topic "Unique Paths", where the difference is:
An obstacle occurs when initializing boundary upstream and columns, and the number of subsequent paths DP is 0
When an obstacle occurs in the middle lattice, the number of paths represented by the grid DP is directly filled in 0
AC Code:
public class Solution {public int uniquepathswithobstacles (int[][] obstaclegrid) { if (obstaclegrid== null| | obstaclegrid.length==0) return 0; int m = obstaclegrid.length; int n = obstaclegrid[0].length; int [] [] DP = new Int[m][n]; for (int i = 0; i < m; i++) { if (obstaclegrid[i][0]!=1) dp[i][0] = 1; else break ; } for (int j = 0; J < N; j + +) { if (obstaclegrid[0][j]!=1) dp[0][j] = 1; else break ; } for (int i = 1, i < m; i++) {for (int j = 1; j< N; j + +) { if (obstaclegrid[i][j]!=1) Dp[i][j] = Dp[i-1][j] + dp[i][j-1]; else dp[i][j]=0; } } return dp[m-1][n-1];} }
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode][java] Unique Paths II