Skip to content

Commit cd28e80

Browse files
refactor 576
1 parent dd7d9b6 commit cd28e80

File tree

1 file changed

+29
-26
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+29
-26
lines changed

src/main/java/com/fishercoder/solutions/_576.java

Lines changed: 29 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -29,36 +29,39 @@
2929
3030
*/
3131
public class _576 {
32-
33-
/**reference: https://leetcode.com/articles/out-of-boundary-paths/#approach-2-recursion-with-memoization-accepted*/
34-
public int findPaths(int m, int n, int N, int x, int y) {
35-
int M = 1000000000 + 7;
36-
int[][] dp = new int[m][n];
37-
dp[x][y] = 1;
38-
int count = 0;
39-
for (int moves = 1; moves <= N; moves++) {
40-
int[][] temp = new int[m][n];
41-
for (int i = 0; i < m; i++) {
42-
for (int j = 0; j < n; j++) {
43-
if (i == m - 1) {
44-
count = (count + dp[i][j]) % M;
45-
}
46-
if (j == n - 1) {
47-
count = (count + dp[i][j]) % M;
48-
}
49-
if (i == 0) {
50-
count = (count + dp[i][j]) % M;
51-
}
52-
if (j == 0) {
53-
count = (count + dp[i][j]) % M;
32+
public static class Solution1 {
33+
/**
34+
* reference: https://leetcode.com/articles/out-of-boundary-paths/#approach-2-recursion-with-memoization-accepted
35+
*/
36+
public int findPaths(int m, int n, int N, int x, int y) {
37+
int M = 1000000000 + 7;
38+
int[][] dp = new int[m][n];
39+
dp[x][y] = 1;
40+
int count = 0;
41+
for (int moves = 1; moves <= N; moves++) {
42+
int[][] temp = new int[m][n];
43+
for (int i = 0; i < m; i++) {
44+
for (int j = 0; j < n; j++) {
45+
if (i == m - 1) {
46+
count = (count + dp[i][j]) % M;
47+
}
48+
if (j == n - 1) {
49+
count = (count + dp[i][j]) % M;
50+
}
51+
if (i == 0) {
52+
count = (count + dp[i][j]) % M;
53+
}
54+
if (j == 0) {
55+
count = (count + dp[i][j]) % M;
56+
}
57+
temp[i][j] = (((i > 0 ? dp[i - 1][j] : 0) + (i < m - 1 ? dp[i + 1][j] : 0)) % M
58+
+ ((j > 0 ? dp[i][j - 1] : 0) + (j < n - 1 ? dp[i][j + 1] : 0)) % M) % M;
5459
}
55-
temp[i][j] = (((i > 0 ? dp[i - 1][j] : 0) + (i < m - 1 ? dp[i + 1][j] : 0)) % M
56-
+ ((j > 0 ? dp[i][j - 1] : 0) + (j < n - 1 ? dp[i][j + 1] : 0)) % M) % M;
5760
}
61+
dp = temp;
5862
}
59-
dp = temp;
63+
return count;
6064
}
61-
return count;
6265
}
6366

6467
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy