Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 7247b13

Browse files
committed
#63 不同路径统计,带障碍物版本
1 parent 803dfad commit 7247b13

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

main/src/dynamic_programming/LC_63_UniquePathsWithObstacles.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,4 +118,33 @@ public int uniquePathsWithObstaclesDP_Review(int[][] obstacleGrid) {
118118

119119
return dp[rows - 1][column - 1];
120120
}
121+
122+
public int uniquePathsWithObstaclesDP_3rd(int[][] obstacleGrid) {
123+
int rows = obstacleGrid.length;
124+
int column = obstacleGrid[0].length;
125+
int[][] dp = new int[rows][column];
126+
if (obstacleGrid[0][0] == 1 || obstacleGrid[rows - 1][column - 1] == 1) {
127+
return 0;
128+
} else {
129+
dp[0][0] = 1;
130+
}
131+
for (int i = 1; i < rows; i++) {
132+
if (obstacleGrid[i][0] != 1) {
133+
dp[i][0] = dp[i - 1][0];
134+
}
135+
}
136+
for (int j = 1; j < column; j++) {
137+
if (obstacleGrid[j][0] != 1) {
138+
dp[0][j] = dp[0][j - 1];
139+
}
140+
}
141+
for (int i = 1; i < rows; i++) {
142+
for (int j = 1; j < column; j++) {
143+
if (obstacleGrid[i][j] != 1) {
144+
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
145+
}
146+
}
147+
}
148+
return dp[rows - 1][column - 1];
149+
}
121150
}

main/test/dynamic_programming/LC_63_UniquePathsWithObstaclesTest.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,21 @@ public void testUniquePathsWithObstaclesDP_Review() {
5151
{{0, 0}, {1, 1}, {0, 0}}
5252
), is(0));
5353
}
54+
55+
@Test
56+
public void testUniquePathsWithObstaclesDP_3RD() {
57+
assertThat(uniquePathsWithObstaclesDomain.uniquePathsWithObstaclesDP_3rd(new int[][]{
58+
{0, 0, 0},
59+
{0, 1, 0},
60+
{0, 0, 0}
61+
}), is(2));
62+
63+
assertThat(uniquePathsWithObstaclesDomain.uniquePathsWithObstaclesDP_3rd(new int[][]{
64+
{1, 0}
65+
}), is(0));
66+
67+
assertThat(uniquePathsWithObstaclesDomain.uniquePathsWithObstaclesDP_3rd(new int[][]
68+
{{0, 0}, {1, 1}, {0, 0}}
69+
), is(0));
70+
}
5471
}

0 commit comments

Comments
 (0)