576. Out of Boundary Paths
Input: m = 2, n = 2, N = 2, i = 0, j = 0
Output: 6
Explanation:
Input: m = 1, n = 3, N = 3, i = 0, j = 1
Output: 12
Explanation:
// Bottom-Up Dynamic Programming
int findPaths(int m, int n, int N, int i, int j) { // time: O(N * m * n); space: O(m * n)
// dp[k][i][j] means the total number of ways to go beyond boundary starting from (i, j) after k steps
// dp[k][i][j] = the total ways to go beyond the boundary from the four neighboring locations of (i, j) with k-1 steps
vector<vector<vector<int> > > dp(N + 1, vector<vector<int> > (m, vector<int>(n, 0)));
for (int k = 1; k <= N; ++k) {
for (int x = 0; x < m; ++x) {
for (int y = 0; y < n; ++y) {
long long up = (x == 0) ? 1 : dp[k - 1][x - 1][y];
long long down = (x == m - 1) ? 1 : dp[k - 1][x + 1][y];
long long left = (y == 0) ? 1 : dp[k - 1][x][y - 1];
long long right = (y == n - 1) ? 1 : dp[k - 1][x][y + 1];
dp[k][x][y] = (up + down + left + right) % 1000000007;
}
}
}
return dp[N][i][j];
}Last updated