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
Example 2:
Input:m = 1, n = 3, N = 3, i = 0, j = 1 Output: 12
思路:dp,方法一,根据上一步的结果,确定本步的结果
代码
public static int findPaths(int m, int n, int N, int i, int j) { long[][][] dp = new long[N + 1][m][n]; for(int step=1;step<N+1;step++) { for(int row=0;row<m;row++) { for (int col=0;col<n;col++) { dp[step][row][col] = ((row == 0 ? 1 : dp[step - 1][row - 1][col]) + (row == m - 1 ? 1 : dp[step - 1][row + 1][col]) + (col == 0 ? 1 : dp[step - 1][row][col - 1]) + (col == n - 1 ? 1 : dp[step - 1][row][col + 1]) )% 1000000007; } } } return (int)dp[N][i][j]; }
思路:由于每次
dp[step][i][j]
只与dp[step-1][i][j]
有关,所以可以优化空间复杂度,用一个二维数组temp记录上一步的状态代码
public static int findPaths(int m, int n, int N, int i, int j) { if (N <= 0) return 0; final int MOD = 1000000007; int[][] count = new int[m][n]; count[i][j] = 1; int result = 0; int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; for (int step = 0; step < N; step++) { int[][] temp = new int[m][n]; for (int r = 0; r < m; r++) { for (int c = 0; c < n; c++) { for (int[] d : dirs) { int nr = r + d[0]; int nc = c + d[1]; if (nr < 0 || nr >= m || nc < 0 || nc >= n) { result = (result + count[r][c]) % MOD; } else { temp[nr][nc] = (temp[nr][nc] + count[r][c]) % MOD; } } } } count = temp; } return result; }