576. Out of Boundary Paths

Problem:

There is an m by n grid with a ball. Given the start coordinate (i,j) of the ball, you can move the ball to adjacent cell or cross the grid boundary in four directions (up, down, left, right). However, you can at most move N times. Find out the number of paths to move the ball out of grid boundary. The answer may be very large, return it after mod 109 + 7.

 

Example 1:

Input: m = 2, n = 2, N = 2, i = 0, j = 0
Output: 6
Explanation:

Example 2:

Input: m = 1, n = 3, N = 3, i = 0, j = 1
Output: 12
Explanation:

 

Note:

  1. Once you move the ball out of boundary, you cannot move it back.
  2. The length and height of the grid is in range [1,50].
  3. N is in range [0,50].

Solutions:

class Solution {
public:
    int findPaths(int m, int n, int N, int i, int j) {
        map<pair<int, int>, int> cache;
        return helper(m, n, N, i, j, cache);
    }

private:
    int helper(int m, int n, int N, int i, int j, map<pair<int, int>, int>& cache) {
        if (i < 0 || i >= m || j < 0 || j >= n) return 1;
        int position = getPosition(m, n, i, j);
        if (cache.count({position, N}) > 0) return cache[{position, N}];

        if (N == 0) return 0;

        int ret = 0;
        for (int k = 0; k < 4; ++k) {
            ret = (ret + helper(m, n, N - 1, i + directions[k][0], j + directions[k][1], cache)) % MOD;
        }

        cache[{position, N}] = ret;
        return ret;
    }

    inline int getPosition(int m, int n, int i, int j) {
        return n * i + j;
    }

    int directions[4][2] = {
        {1, 0},
        {-1, 0},
        {0, 1},
        {0, -1}
    };

    int MOD = 1e9 + 7;
};

results matching ""

    No results matching ""