LeetCode 576: Out of Boundary Paths Solution

Master LeetCode problem 576 (Out of Boundary Paths), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

576. Out of Boundary Paths

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. We can create a 3D array dp where dp[i][j][k] represents the number of ways to move the ball to position (i, j) after making k moves. We initialize the array with dp[startRow][startColumn][0] = 1 since the ball is already at the starting position.

For each move, we update the dp array based on the number of ways to reach the current position (i, j) from its adjacent positions. We also keep track of the number of paths that move out of the boundary, which is when the current position is on the boundary.

Finally, we sum up the count of paths that move out of the boundary for maxMove moves and return the result modulo 10^9 + 7.

Time Complexity: O(m * n * maxMove) Space Complexity: O(m * n * maxMove)

Solution Code

class Solution {
    public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
        int MOD = 1000000007;
        int[][][] dp = new int[m][n][maxMove + 1];
        dp[startRow][startColumn][0] = 1;

        int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        int count = 0;

        for (int move = 1; move <= maxMove; move++) {
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    for (int[] dir : dirs) {
                        int newRow = i + dir[0];
                        int newCol = j + dir[1];

                        if (newRow < 0 || newRow >= m || newCol < 0 || newCol >= n) {
                            count = (count + dp[i][j][move - 1]) % MOD;
                        } else {
                            dp[newRow][newCol][move] = (dp[newRow][newCol][move] + dp[i][j][move - 1]) % MOD;
                        }
                    }
                }
            }
        }

        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 576 (Out of Boundary Paths)?

This page provides optimized solutions for LeetCode problem 576 (Out of Boundary Paths) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 576 (Out of Boundary Paths)?

The time complexity for LeetCode 576 (Out of Boundary Paths) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 576 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 576 in Java, C++, or Python.

Back to LeetCode Solutions