Skip to main content
Back to problems
#576
Medium Algorithms

Out of boundary paths

Dynamic Programming
48.4% acceptance
Jan 13, 2026
3985
296
There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball. Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn find_paths(m: i32, n: i32, max_move: i32, start_row: i32, start_column: i32) -> i32 {
    const MOD: i64 = 1_000_000_007;
    let (m, n) = (m as usize, n as usize);
    let mut dp = vec![vec![0i64; n]; m];
    dp[start_row as usize][start_column as usize] = 1;
    let mut result = 0i64;
    let dirs: [(i32, i32); 4] = [(-1, 0), (1, 0), (0, -1), (0, 1)];
    for _ in 0..max_move {
      let mut ndp = vec![vec![0i64; n]; m];
      for i in 0..m {
        for j in 0..n {
          if dp[i][j] == 0 { continue; }
          for &(di, dj) in &dirs {
            let ni = i as i32 + di;
            let nj = j as i32 + dj;
            if ni < 0 || ni >= m as i32 || nj < 0 || nj >= n as i32 {
              result = (result + dp[i][j]) % MOD;
            } else {
              ndp[ni as usize][nj as usize] = (ndp[ni as usize][nj as usize] + dp[i][j]) % MOD;
            }
          }
        }
      }
      dp = ndp;
    }
    result as i32
  }
}