[LeetCode] Out of Boundary Paths

576. Out of Boundary Paths

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
int dx[4] = {0, 1, 0, -1};
int dy[4] = {-1, 0, 1, 0};
int MOD = 1e9+7;
public:
int findPaths(int m, int n, int N, int i, int j) {
int res = 0;
vector<map<pair<int,int>, int>> ball(N + 1, map<pair<int,int>, int>());

ball[N][{i + 1, j + 1}]++;
for(int move = N; move >= 1; move--) {
for(auto& pos : ball[move]) {
auto& p = pos.first;
for(int i = 0; i < 4; i++) {
int ny = p.first + dy[i];
int nx = p.second + dx[i];
if(0 < nx && nx <= n && 0 < ny && ny <= m) {
ball[move - 1][{ny, nx}] = (ball[move - 1][{ny, nx}] + pos.second) % MOD;
}
if((p.first == 1 || p.first == m || p.second == 1 || p.second == n) && (ny == 0 || nx == 0 || ny == m + 1 || nx == n + 1)) {
res = (res + pos.second) % MOD;
}
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/13/PS/LeetCode/out-of-boundary-paths/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.