
Sponsored
Sponsored
The main idea is to use a 3D dynamic programming array dp[i][j][k] where i and j represent the current position on the grid, and k represents the number of moves remaining. The value at dp[i][j][k] represents the number of ways to move the ball out of bounds using at most k moves starting from (i, j).
Transitions are made by moving the ball in one of the four possible directions and decreasing the move count. If the ball goes out of bounds, increment the path count. The answer is the sum of paths from startRow, startColumn using maxMove moves.
Time Complexity: O(m * n * maxMove) as each grid cell and move combination is processed exactly once.
Space Complexity: O(m * n * maxMove) due to the storage of the DP array.
1#include <stdio.h>
2#define MOD 1000000007
3
4int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
5 int dp[51][51][51] = {{{0}}};
6 int directions[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
7 dp[startRow][startColumn][0] = 1;
8 int count = 0;
9 for (int move = 1; move <= maxMove; move++) {
10 for (int i = 0; i < m; i++) {
11 for (int j = 0; j < n; j++) {
12 for (int d = 0; d < 4; d++) {
13 int ni = i + directions[d][0];
14 int nj = j + directions[d][1];
15 if (ni < 0 || nj < 0 || ni >= m || nj >= n) {
16 count = (count + dp[i][j][move-1]) % MOD;
17 } else {
18 dp[ni][nj][move] = (dp[ni][nj][move] + dp[i][j][move-1]) % MOD;
19 }
20 }
21 }
22 }
23 }
24 return count;
25}
26
27int main() {
28 printf("%d\n", findPaths(2, 2, 2, 0, 0)); // Output: 6
29 printf("%d\n", findPaths(1, 3, 3, 0, 1)); // Output: 12
30 return 0;
31}This C solution initializes a 3D DP array to store the number of paths achieving out-of-bounds through various moves. It iterates over possible moves and transitions the current position to its adjacent cells, checking for out-of-bound conditions to increment the path count. The results are accumulated for all cells and moves.
DFS with memoization is used to prevent recalculating results for already evaluated states by storing them in a map or dictionary. Each call is a recursive attempt to move in all directions from the current cell, decrementing the move count. Result of out-of-bounds attempts is stored so it can be reused, avoiding exponential time complexity.
This algorithm uses a function that considers the current position and remaining moves. For every call, explore in four possible directions and add to the path count if the ball gets out of bounds. Store already calculated counts in a dictionary for path optimization.
Time Complexity: O(m * n * maxMove) where each state is visited only once.
Space Complexity: O(m * n * maxMove) due to memoization storage.
This C solution initializes a memo array for caching recursive calls. The dfs function recursively explores all four movement directions. When the ball falls out of bounds, it contributes to the path count. Memoization avoids repeated calculations, ensuring efficiency.