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.
与Unique Paths一样,只是多了一个判断:如果该点存在障碍,从它出发的路线条数为0.
package leetcode;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class UniquePathsII {
static {
System.setIn(UniquePaths.class.getResourceAsStream("/data/leetcode/UniquePaths.txt"));
}
private static StreamTokenizer stdin = new StreamTokenizer(new InputStreamReader(System.in));
private static int readInt() throws IOException {
stdin.nextToken();
return (int) stdin.nval;
}
/**
* @param args
*/
public static void main(String[] args) throws IOException {
int[][] a = new int[1][2];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = readInt();
}
}
UniquePathsII s = new UniquePathsII();
int ss = s.uniquePathsWithObstacles(a);
System.out.println(ss);
}
private long[][] result;
int mm;
int nn;
int[][] obstacleGrid;
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
mm = obstacleGrid[0].length;
nn = obstacleGrid.length;
this.obstacleGrid = obstacleGrid;
result = new long[nn+1][mm+1];
if (hasObstacle(1,1)) {
return 0;
} else {
result[1][1] = 1;
}
for (int m = 2; m <= mm; m++) {
int n = 1;
if (hasObstacle(m,n)) {
result[n][m] = 0;
} else {
result[n][m] = result[n][m - 1];
}
}
for (int n = 2; n <= nn; n++) {
int m = 1;
if (hasObstacle(m,n)) {
result[n][m] = 0;
} else {
result[n][m] = result[n - 1][m];
}
}
int d = 2;
while (d <= Math.max(mm, nn)) {
if (d <= mm) {
for (int n = d; n <= nn; n++) {
if (!hasObstacle(d, n)) {
result[n][d] = result[n - 1][d] + result[n][d - 1];
} else {
result[n][d] = 0;
}
}
}
if (d <= nn) {
for (int m = d; m <= mm; m++) {
if (!hasObstacle(m, d)) {
result[d][m] = result[d - 1][m] + result[d][m - 1];
} else {
result[d][m] = 0;
}
}
}
d++;
}
return (int) this.result[nn][mm];
}
private boolean hasObstacle(int m, int n) {
int x = nn - n;
int y = mm - m;
return obstacleGrid[x][y] == 1;
}
}