有多少种方法能把足球移出边界 Out of Boundary Paths
為什么80%的碼農都做不了架構師?>>> ??
問題:
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 10^9?+ 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:
解決:
【題意】給定一個二維的數組,某個位置放個足球,每次可以在上下左右四個方向中任意移動一步,總共可以移動N步,問我們總共能有多少種移動方法能把足球移除邊界。
① ?動態規劃,對于這種結果很大的數如果用遞歸解法很容易爆棧,所以最好考慮使用DP來解。
dp[k][i][j]表示總共走k步,從(i,j)位置走出邊界的總路徑數。對于dp[k][i][j],走k步出邊界的總路徑數等于其周圍四個位置的走k-1步出邊界的總路徑數之和,如果周圍某個位置已經出邊界了,那么就直接加上1,否則就在dp數組中找出該值,這樣整個更新下來,我們就能得出每一個位置走任意步數的出界路徑數了,最后只要返回dp[N][i][j]就是所求結果了。
class Solution { //46ms
? ? public int findPaths(int m, int n, int N, int i, int j) {
? ? ? ? long[][][] dp = new long[N + 1][m][n];
? ? ? ? for (int k = 1;k <= N;k ++){
? ? ? ? ? ? for (int x = 0;x < m;x ++){
? ? ? ? ? ? ? ? for (int y = 0;y < n;y ++){
? ? ? ? ? ? ? ? ? ? long v1 = (x == 0) ? 1 : dp[k - 1][x - 1][y];
? ? ? ? ? ? ? ? ? ? long v2 = (x == m - 1) ? 1 : dp[k - 1][x + 1][y];
? ? ? ? ? ? ? ? ? ? long v3 = (y == 0) ? 1 : dp[k - 1][x][y - 1];
? ? ? ? ? ? ? ? ? ? long v4 = (y == n - 1) ? 1 : dp[k - 1][x][y + 1];
? ? ? ? ? ? ? ? ? ? dp[k][x][y] = (v1 + v2 + v3 + v4) % 1000000007;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return (int)dp[N][i][j];
? ? }
}
② 在discuss中看到的,dfs。
class Solution { //12ms
? ? public int findPaths(int m, int n, int N, int i, int j) {
? ? ? ? int[][][] dp = new int[m][n][N + 1];
? ? ? ? return dfs(dp,i,j,N) % 1000000007;
? ? }
? ? int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
? ? public int dfs(int[][][] dp,int i,int j,int N){
? ? ? ? if(i < 0 || j < 0 || i >= dp.length || j >= dp[0].length) return 1;
? ? ? ? if(i - N >= 0 && i + N < dp.length && j - N >= 0 && j + N < dp[0].length) return 0;
? ? ? ? if(N <= 0) return 0;
? ? ? ? if(dp[i][j][N] > 0) return dp[i][j][N];
? ? ? ? int count = 0;
? ? ? ? for(int[] dir : dirs){
? ? ? ? ? ? int x = i + dir[0];
? ? ? ? ? ? int y = j + dir[1];
? ? ? ? ? ? count += dfs(dp,x,y,N-1) % 1000000007;
? ? ? ? ? ? count %= 1000000007;
? ? ? ? }
? ? ? ? dp[i][j][N] = count;
? ? ? ? return count;
? ? }
}
轉載于:https://my.oschina.net/liyurong/blog/1605405
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的有多少种方法能把足球移出边界 Out of Boundary Paths的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第五周学习笔记
- 下一篇: U盘安装LINUX系统,拔除U盘后无法引