Skip to content

Commit 2a35f24

Browse files
committed
Add solution #576
1 parent 60acd07 commit 2a35f24

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,7 @@
452452
567|[Permutation in String](./0567-permutation-in-string.js)|Medium|
453453
572|[Subtree of Another Tree](./0572-subtree-of-another-tree.js)|Easy|
454454
575|[Distribute Candies](./0575-distribute-candies.js)|Easy|
455+
576|[Out of Boundary Paths](./0576-out-of-boundary-paths.js)|Medium|
455456
589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy|
456457
594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy|
457458
599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy|
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 576. Out of Boundary Paths
3+
* https://leetcode.com/problems/out-of-boundary-paths/
4+
* Difficulty: Medium
5+
*
6+
* There is an m x n grid with a ball. The ball is initially at the position [startRow,
7+
* startColumn]. You are allowed to move the ball to one of the four adjacent cells in
8+
* the grid (possibly out of the grid crossing the grid boundary). You can apply at most
9+
* maxMove moves to the ball.
10+
*
11+
* Given the five integers m, n, maxMove, startRow, startColumn, return the number of
12+
* paths to move the ball out of the grid boundary. Since the answer can be very large,
13+
* return it modulo 109 + 7.
14+
*/
15+
16+
/**
17+
* @param {number} m
18+
* @param {number} n
19+
* @param {number} maxMove
20+
* @param {number} startRow
21+
* @param {number} startColumn
22+
* @return {number}
23+
*/
24+
var findPaths = function(m, n, maxMove, startRow, startColumn) {
25+
const MOD = 1e9 + 7;
26+
const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];
27+
const dp = new Array(maxMove + 1).fill().map(() => {
28+
return new Array(m).fill().map(() => new Array(n).fill(-1));
29+
});
30+
31+
return solve(maxMove, startRow, startColumn);
32+
33+
function solve(moves, row, col) {
34+
if (row < 0 || row >= m || col < 0 || col >= n) return 1;
35+
if (moves === 0) return 0;
36+
if (dp[moves][row][col] !== -1) return dp[moves][row][col];
37+
38+
let paths = 0;
39+
for (const [dr, dc] of directions) {
40+
paths = (paths + solve(moves - 1, row + dr, col + dc)) % MOD;
41+
}
42+
return dp[moves][row][col] = paths;
43+
}
44+
};

0 commit comments

Comments
 (0)