算法作业21

来源:互联网 发布:上海数据开放平台 编辑:程序博客网 时间:2024/06/02 06:25

题目地址:https://leetcode.com/problems/out-of-boundary-paths/#/description

题目描述: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.

我的代码

class Solution {public:    int I_M = 1000000007;    int findPaths(int m, int n, int N, int i, int j) {        if(N == 0) return 0;        long long a[m][n][N];        for(int k=0;k<m;k++)        for(int l=0;l<n;l++){            a[k][l][0]=0;        }        for(int l=0;l<n;l++){            a[0][l][0]+=1;            a[m-1][l][0]+=1;        }        for(int k=0;k<m;k++){            a[k][0][0]+=1;            a[k][n-1][0]+=1;        }        int dis[4][2] = {-1,0,1,0,0,-1,0,1};           for(int ni=1;ni<N;ni++){            for(int k=0;k<m;k++)            for(int l=0;l<n;l++){                a[k][l][ni]=0;                for(int d=0;d<4;d++)                if(k+dis[d][0]>=0&&l+dis[d][1]>=0&&k+dis[d][0]<m&&l+dis[d][1]<n)                    a[k][l][ni]=(a[k][l][ni]+a[k+dis[d][0]][l+dis[d][1]][ni-1])%I_M;            }        }        long long num = 0;        for(int k=0;k<N;k++){            num=(num+a[i][j][k])%I_M;        }        return num;    }};

解题思路
球走出方格的步数可能为1,2,3,……N。一种很简单的思路就是分别求出恰好走1,2,3,……N步走出方格的可能的情况。
而没走一步,或者走出方格,或者走到相邻的方格,且步数减一,由此,可以通过相邻方格巧合走k步的可能情况来求一个方格恰好走k+1步的可能情况。
因此,可以用一个简单的动态规划来求解此题,用a[i][j][ni]记录第(i,j)位置恰好ni+1(因为0步的可能情况必然为0,无需考虑)步走出方格的可能情况,对ni进行动态规划,ni为0时,只有边界点可以走出去,对边界点初始化即可。ni不为0时,第一步一定是走到相邻的方格,然后再走ni步,所以等于所有相邻方格的a[i][j][ni-1]之和。
最后的结果就是(i,j)位置的s[i][j][ni],ni=0,1,2……N-1,之和。
复杂度为O(mnN)。