|
| 1 | +// Source : https://oj.leetcode.com/problems/unique-paths-ii/ |
| 2 | +// Inspired by : http://www.jiuzhang.com/solutions/unique-paths/ |
| 3 | +// Author : Lei Cao |
| 4 | +// Date : 2015-10-11 |
| 5 | + |
| 6 | +/********************************************************************************** |
| 7 | + * |
| 8 | + * Follow up for "Unique Paths": |
| 9 | + * |
| 10 | + * Now consider if some obstacles are added to the grids. How many unique paths would there be? |
| 11 | + * |
| 12 | + * An obstacle and empty space is marked as 1 and 0 respectively in the grid. |
| 13 | + * |
| 14 | + * For example, |
| 15 | + * There is one obstacle in the middle of a 3x3 grid as illustrated below. |
| 16 | + * |
| 17 | + * [ |
| 18 | + * [0,0,0], |
| 19 | + * [0,1,0], |
| 20 | + * [0,0,0] |
| 21 | + * ] |
| 22 | + * |
| 23 | + * The total number of unique paths is 2. |
| 24 | + * |
| 25 | + * Note: m and n will be at most 100. |
| 26 | + * |
| 27 | + **********************************************************************************/ |
| 28 | + |
| 29 | +package dynamicProgramming.uniquePaths; |
| 30 | + |
| 31 | +public class uniquePathsII { |
| 32 | + /** |
| 33 | + * @param obstacleGrid: A list of lists of integers |
| 34 | + * @return: An integer |
| 35 | + */ |
| 36 | + public int uniquePathsWithObstacles(int[][] obstacleGrid) { |
| 37 | + if (obstacleGrid.length == 0 || obstacleGrid[0].length ==0) { |
| 38 | + return 0; |
| 39 | + } |
| 40 | + if (obstacleGrid[0][0] == 1) { |
| 41 | + return 0; |
| 42 | + } |
| 43 | + int m = obstacleGrid.length; |
| 44 | + int n = obstacleGrid[0].length; |
| 45 | + // write your code here |
| 46 | + int[][] matrix = new int[m][n]; |
| 47 | + for (int i = 0; i < m; i++) { |
| 48 | + if (obstacleGrid[i][0] != 1) { |
| 49 | + matrix[i][0] = 1; |
| 50 | + } else { |
| 51 | + break; |
| 52 | + } |
| 53 | + } |
| 54 | + for (int i = 0; i < n; i++) { |
| 55 | + if (obstacleGrid[0][i] != 1) { |
| 56 | + matrix[0][i] = 1; |
| 57 | + } else { |
| 58 | + break; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + for (int i = 1; i < m; i++) { |
| 63 | + for (int j = 1; j < n; j++) { |
| 64 | + if (obstacleGrid[i][j] == 1) { |
| 65 | + matrix[i][j] = 0; |
| 66 | + } else { |
| 67 | + matrix[i][j] = matrix[i-1][j] + matrix[i][j-1]; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + return matrix[m-1][n-1]; |
| 72 | + } |
| 73 | +} |
0 commit comments