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.
01 public int uniquePathsWithObstacles(int[][] obstacleGrid) {
02 int m=obstacleGrid.length;
03 if(m==0)
04 return 0;
05 int n=obstacleGrid[0].length;
06 if(n==0)
07 return 0;
08 int [][]results=new int[m][n];
09 if(obstacleGrid[0][0]==0)
10 {
11 results[0][0]=1;
12 }
13
14 else
15 {
16 results[0][0]=0;
17 }
18
19 for(int i=1;i<m;i++)
20 {
21 if(obstacleGrid[i][0]==0)
22 {
23 results[i][0]=results[i-1][0];
24 }
25 else
26 {
27 results[i][0]=0;
28 }
29 }
30 for(int j=1;j<n;j++)
31 {
32 if(obstacleGrid[0][j]==0)
33 {
34 results[0][j]=results[0][j-1];
35 }
36 else
37 {
38 results[0][j]=0;
39 }
40
41 }
42
43 for(int i=1;i<m;i++)
44 {
45 for(int j=1;j<n;j++)
46 {
47 if(obstacleGrid[i][j]==0)
48 {
49 results[i][j]=results[i-1][j]+results[i][j-1];
50 }
51 else
52 {
53 results[i][j]=0;
54 }
55 }
56 }
57 return results[m-1][n-1];
58 }
03 if(m==0)
04 return 0;
05 int n=obstacleGrid[0].length;
06 if(n==0)
07 return 0;
08 int [][]results=new int[m][n];
09 if(obstacleGrid[0][0]==0)
10 {
11 results[0][0]=1;
12 }
13
14 else
15 {
16 results[0][0]=0;
17 }
18
19 for(int i=1;i<m;i++)
20 {
21 if(obstacleGrid[i][0]==0)
22 {
23 results[i][0]=results[i-1][0];
24 }
25 else
26 {
27 results[i][0]=0;
28 }
29 }
30 for(int j=1;j<n;j++)
31 {
32 if(obstacleGrid[0][j]==0)
33 {
34 results[0][j]=results[0][j-1];
35 }
36 else
37 {
38 results[0][j]=0;
39 }
40
41 }
42
43 for(int i=1;i<m;i++)
44 {
45 for(int j=1;j<n;j++)
46 {
47 if(obstacleGrid[i][j]==0)
48 {
49 results[i][j]=results[i-1][j]+results[i][j-1];
50 }
51 else
52 {
53 results[i][j]=0;
54 }
55 }
56 }
57 return results[m-1][n-1];
58 }
没有评论:
发表评论