Unique Path Series

Unique Paths I

Question

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).

How many possible unique paths are there?

Analysis

Java DP solution with complexity O(n*m)

最左侧和最上侧的一列的行走方式都只有1种,除此之外的每个格子的路径个数是他的上方相邻格和左侧相邻格的路径个数和

Code

2-D array version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {
public int uniquePaths(int m, int n) {
int[][] map=new int[m][n];
for(int i=0;i<m;i++)
map[i][0]=1;
for(int i=0;i<n;i++)
map[0][i]=1;
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
map[i][j]=map[i][j-1]+map[i-1][j];
}
}
return map[m-1][n-1];
}
}

1-D array version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public int uniquePaths(int m, int n) {
if (m == 0 || n == 0) {
return 0;
}
if (m == 1 || n == 1) {
return 1;
}
int[] dp = new int[n];
for (int i = 0; i < n; i++) {
dp[i] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[j] += dp[j - 1];
}
}
return dp[n - 1];
}

Unique Paths II

Question

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.

1
2
3
4
5
[
[0,0,0],
[0,1,0],
[0,0,0]
]

The total number of unique paths is 2.

Analysis

重点在于确定好最左侧和最上方行列的路径个数

  • (0,0)位置有阻碍则map为0,否则为1
  • 左侧和上方的当前格子路径个数都等于前一个*1,即假如上一个格子的路径数已经为0,其后所有的格子的路径数都为0
  • 其余格子计算同上

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m=obstacleGrid.length;
if(m==0)
return 0;
int n=obstacleGrid[0].length;
int[][] map=new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(obstacleGrid[i][j]==1)
map[i][j]=0;
else if(i==0&&j==0){
if(obstacleGrid[i][j]==1)
map[i][j]=0;
else
map[i][j]=1;
}
else if(i==0)
map[i][j]=map[i][j-1]*1;
else if(j==0)
map[i][j]=map[i-1][j]*1;
else
map[i][j]=map[i-1][j]+map[i][j-1];
}
}
return map[m-1][n-1];
}
}

####