### LeetCode  • ㊗️
• 大家
• offer
• 多多！

## Problem

There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.

Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 10^9 + 7.

Example 1: Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
Output: 6


Example 2: Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
Output: 12


Constraints:

• 1 <= m, n <= 50
• 0 <= maxMove <= 50
• 0 <= startRow < m
• 0 <= startColumn < n

## Code

688. Knight Probability in Chessboard

class Solution {
public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int MOD = 1000000007;

int[][] dp = new int[m][n];
int res = 0;

dp[startRow][startColumn] = 1;

for (int step = 0; step < maxMove; step++) {
int[][] curr = new int[m][n];

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if(dp[i][j] == 0) continue;

for (int[] dir : dirs) {
int x = i + dir;
int y = j + dir;

if (x < 0 || x >= m || y < 0 || y >= n) {
res = (res + dp[i][j]) % MOD;
} else {
curr[x][y] = (curr[x][y] + dp[i][j]) % MOD;
}
}
}
}

dp = curr;
}

return res;
}
}