zoukankan      html  css  js  c++  java
  • LeetCode 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.

    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:

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

    分析

    动态规划

    class Solution {
    public:
        int findPaths(int m, int n, int N, int i, int j) {
            if(N==0) return 0;
            uint t=pow(10,9);
            vector<vector<uint>> dp(m,vector<uint>(n,0));
            for(int step=1;step<=N;step++){
                vector<vector<uint>> temp(m,vector<uint>(n,0));
                for(int p=0;p<m;p++)
                    for(int q=0;q<n;q++){
                        if(p!=0)
                           temp[p][q]+=dp[p-1][q];
                        else
                           temp[p][q]++;
                        if(p!=m-1)
                           temp[p][q]+=dp[p+1][q];
                        else
                           temp[p][q]++;
                        if(q!=0)
                           temp[p][q]+=dp[p][q-1];
                        else
                           temp[p][q]++;
                        if(q!=n-1)
                           temp[p][q]+=dp[p][q+1];
                        else
                           temp[p][q]++;
                        temp[p][q]=temp[p][q]%(1000000007);
                    }
              dp=temp;
            }
            return dp[i][j];
        }
    };
    
  • 相关阅读:
    李超线段树 (Li-Chao Segment Tree)
    NowCoder Contest 894
    AtCoder Beginning Contest 126
    华工软院IBM LinuxONE Community Cloud云计算实验文档
    Codeforces Round #561 (div. 2)
    Comet OJ Contest #3
    Codeforces Edu Round 65 (Rated for Div. 2)
    莫队算法 (Mo's Algorithm)
    Codeforces Round #559 (Div. 2)
    GDCPC2019 广东省赛总结
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/10074022.html
Copyright © 2011-2022 走看看