# [C++] DP solution

• A few people have posted very nice solutions using DP. Here is another one.
One feature is that I expand the grid by one cell in all four directions, by assigning the number of paths using 0 times of moves to be 1.

class Solution {
public:
int findPaths(int m, int n, int N, int i, int j) {
if (N == 0) return 0;
long mod = 1000000007;
vector<vector<vector<long>>> dp (m + 2, vector<vector<long>> (n + 2, vector<long> (N + 1, 0)));    // dp[k][l][p] number of paths for starting at (k, l) with p times
long result = 0;
for (int k = 1; k <= m; k ++) {
dp[k][0][0] = 1;
dp[k][n + 1][0] = 1;
}
for (int l = 1; l <= n; l++) {
dp[0][l][0] = 1;
dp[m + 1][l][0] = 1;
}

for (int p = 1; p <= N; p++) {
for (int layer = 0; layer < min(m, n) / 2.0; layer ++) {
for (int k = layer + 1; k <= m - layer; k ++) {
for (int l = layer + 1; l <= n -layer; l++) {
dp[k][l][p] = dp[k - 1][l][p - 1] + dp[k + 1][l][p - 1] + dp[k][l - 1][p - 1] + dp[k][l + 1][p - 1];
dp[k][l][p] %= mod;
}
}
}
}
for (int u = 1; u <= N; u++) {
result += dp[i + 1][j + 1][u];
result %= mod;
}
return result % mod;
}
};

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.