MCPcopy Create free account
hub / github.com/Blankj/awesome-java-leetcode / Solution

Class Solution

src/com/blankj/medium/_0067/Solution.java:11–40  ·  view source on GitHub ↗

author: Blankj blog : http://blankj.com time : 2020/07/07 desc :

Source from the content-addressed store, hash-verified

9 * </pre>
10 */
11public class Solution {
12 public int uniquePathsWithObstacles(int[][] obstacleGrid) {
13 int m = obstacleGrid.length, n = obstacleGrid[0].length;
14 int[][] dp = new int[m][n];
15 // 其初始态第 1 列(行)的格子只有从其上(左)边格子走过去这一种走法,
16 // 因此初始化 dp[i][0](dp[0][j])值为 1,且遇到障碍物时后面值都为 0;
17 for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) {
18 dp[i][0] = 1;
19 }
20 for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) {
21 dp[0][j] = 1;
22 }
23
24 for (int i = 1; i < m; i++) {
25 for (int j = 1; j < n; j++) {
26 if (obstacleGrid[i][j] == 0) {
27 // 当 (i, j) 有障碍物时,dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
28 dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
29 }
30 }
31 }
32 return dp[m - 1][n - 1];
33 }
34
35 public static void main(String[] args) {
36 Solution solution = new Solution();
37 int[][] obstacleGrid = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}};
38 System.out.println(solution.uniquePathsWithObstacles(obstacleGrid));
39 }
40}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected