Skip to main content
Back to problems
#1301
Hard Algorithms

Number of paths with max score

Array Dynamic Programming Matrix
42.1% acceptance
Feb 25, 2026
550
28
You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S'. You need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there. Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7. In case there is no path, return [0, 0].

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
const MOD: i64 = 1_000_000_007;

impl Solution {
  pub fn paths_with_max_score(board: Vec<String>) -> Vec<i32> {
    let n = board.len();
    let grid: Vec<Vec<u8>> = board.iter().map(|r| r.bytes().collect()).collect();
    // dp[i][j] = (max_sum, count)
    let mut dp = vec![vec![(-1i64, 0i64); n]; n];
    dp[n - 1][n - 1] = (0, 1);

    for i in (0..n).rev() {
      for j in (0..n).rev() {
        if i == n - 1 && j == n - 1 { continue; }
        if grid[i][j] == b'X' { continue; }
        let mut best = -1i64;
        let mut cnt = 0i64;
        // from (i+1, j), (i, j+1), (i+1, j+1)
        let neighbors = [(i + 1, j), (i, j + 1), (i + 1, j + 1)];
        for &(ni, nj) in &neighbors {
          if ni < n && nj < n && dp[ni][nj].0 >= 0 {
            let (s, c) = dp[ni][nj];
            if s > best { best = s; cnt = c; }
            else if s == best { cnt = (cnt + c) % MOD; }
          }
        }
        if best < 0 { continue; }
        let cell_val = if grid[i][j] == b'E' || grid[i][j] == b'S' { 0 } else { (grid[i][j] - b'0') as i64 };
        dp[i][j] = (best + cell_val, cnt % MOD);
      }
    }
    if dp[0][0].0 < 0 {
      vec![0, 0]
    } else {
      vec![dp[0][0].0 as i32, dp[0][0].1 as i32]
    }
  }
}