576. Out of Boundary Paths

Difficulty:
Related Topics:
Similar Questions:

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 109 + 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:

Solution

/**
 * @param {number} m
 * @param {number} n
 * @param {number} maxMove
 * @param {number} startRow
 * @param {number} startColumn
 * @return {number}
 */
var findPaths = function(m, n, maxMove, startRow, startColumn) {
    var matrix = Array(m).fill(0).map(() => Array(n).fill(0));
    matrix[startRow][startColumn] = 1;
    var res = 0;
    var mod = Math.pow(10, 9) + 7;
    for (var k = 0; k < maxMove; k++) {
        var newMatrix = Array(m).fill(0).map(() => Array(n).fill(0));
        for (var i = 0; i < m; i++) {
            for (var j = 0; j < n; j++) {
                newMatrix[i][j] = (
                    (matrix[i - 1] ? matrix[i - 1][j] : 0) +
                    (matrix[i][j - 1] || 0) +
                    (matrix[i + 1] ? matrix[i + 1][j] : 0) +
                    (matrix[i][j + 1] || 0)
                ) % mod;
                if (i === 0) res += matrix[i][j];
                if (i === m - 1) res += matrix[i][j];
                if (j === 0) res += matrix[i][j];
                if (j === n - 1) res += matrix[i][j];
                res %= mod;
            }
        }
        matrix = newMatrix;
    }
    return res;
};

Explain:

Dynamic programming.

Complexity: