Skip to content

1301. Number of Paths with Max Score

Description

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].

 

Example 1:

Input: board = ["E23","2X2","12S"]
Output: [7,1]

Example 2:

Input: board = ["E12","1X1","21S"]
Output: [4,2]

Example 3:

Input: board = ["E11","XXX","11S"]
Output: [0,0]

 

Constraints:

  • 2 <= board.length == board[i].length <= 100

 

Solutions

Solution: Dynamic Programming

  • Time complexity: O(n2)
  • Space complexity: O(n2)

 

JavaScript

js
/**
 * @param {string[]} board
 * @return {number[]}
 */
const pathsWithMaxScore = function (board) {
  const OBSTACLE = 'X';
  const START = 'S';
  const GOAL = 'E';
  const MODULO = 10 ** 9 + 7;
  const n = board.length;
  const directions = [
    [1, 0],
    [0, 1],
    [1, 1],
  ];
  const dp = Array.from({ length: n }, () => new Array(n).fill(Number.MIN_SAFE_INTEGER));
  const paths = Array.from({ length: n }, () => new Array(n).fill(0));

  dp[0][0] = 0;
  paths[0][0] = 1;

  for (let row = 0; row < n; row++) {
    for (let col = 0; col < n; col++) {
      const value = board[row][col];
      const path = paths[row][col];

      if (value === OBSTACLE || !path) continue;
      const score = value === START || value === GOAL ? 0 : Number(value);

      for (const [moveRow, moveCol] of directions) {
        const nextRow = row + moveRow;
        const nextCol = col + moveCol;

        if (nextRow >= n || nextCol >= n) continue;
        const newScore = (score + dp[row][col]) % MODULO;
        const nextScore = dp[nextRow][nextCol];
        const nextPath = paths[nextRow][nextCol];

        if (newScore > nextScore) {
          dp[nextRow][nextCol] = newScore;
          paths[nextRow][nextCol] = path;
        } else if (newScore === nextScore) {
          paths[nextRow][nextCol] = (path + nextPath) % MODULO;
        }
      }
    }
  }
  const score = dp[n - 1][n - 1];
  const path = paths[n - 1][n - 1];

  return [score === Number.MIN_SAFE_INTEGER ? 0 : score, path];
};

Released under the MIT license