Package Cn.edu.xidian.sselab.array;
/**
*
* @author Zhiyong Wang
* Title:unique Paths II
* Content:
* 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 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.
*
*/
public class Uniquepathsii {
Recursion didn't figure out how to do it, but this is like Pascaltriangle.
/**
* 1 1 1 1
* 1 2 3 4
* 1 3 6 10
* 1 4 10 20
* 4*4 table, up to 20 routes, if there is a barrier, change the barrier to 0, change the non-barrier to 1
* I did not think of a solution, the last look at the answer: the idea is this, first judge (0,0) the value, and then initialize the first row with the first column value,
* The first value is 0 to 1, 1 to 0, when the row is initialized, if the current value is 1, then 0, if 0, the previous value assigns it
* When initializing a column, the current value is 1, then 0 and if 0, the previous value is assigned to it
* After initialization is complete, it is to start judging all the remaining values, if you encounter 1, then set to 0, if you encounter 0, then go above the value and the value of the first face and as the point
*/
public int uniquepathswithobstacles (int[][] obstaclegrid) {
int length = Obstaclegrid.length;
int width = obstaclegrid[0].length;
The first step is to initialize the first row and the first column first
Obstaclegrid[0][0] ^= 1;
for (int i=1;i<width;i++)
Obstaclegrid[0][i] = obstaclegrid[0][i]==1?0:obstaclegrid[0][i-1];
for (int i=1;i<length;i++)
Obstaclegrid[i][0] = obstaclegrid[i][0]==1?0:obstaclegrid[i-1][0];
The second step is to find the last path and
for (int i=1;i<length;i++) {
for (int j=1;j<width;j++) {
OBSTACLEGRID[I][J] = obstaclegrid[i][j]==1?0:obstaclegrid[i-1][j]+obstaclegrid[i][j-1];
}
}
return obstaclegrid[length-1][width-1];
}
}
Unique Paths II