576. Out of Boundary Paths

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;
       }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值