Problem Description
Given a square board where each cell contains either a digit ('1'-'9'), an obstacle ('X'), the start ('S' at the bottom-right), or the end ('E' at the top-left), find the maximum sum obtainable by moving from S to E. Allowed moves are upward, leftward, or diagonally up-left. Additionally, compute the number of distinct paths that yield this maximum sum, with the count returned modulo 10^9+7. If no valid path exists, return [0, 0].
Key Insights
- Use dynamic programming (DP) traversing the board in reverse (from start 'S' backwards to end 'E').
- Maintain a DP table where each cell holds a pair: (max score achievable from that cell to the end, count of paths that achieve that score).
- Transitions consider three possible moves (up, left, diagonal up-left) and pick the best outcome.
- Sum the numeric value of the current cell (if it is not 'S' or 'E') to contributions from the next moves.
- Carefully handle obstacles ('X') by skipping them in the DP update.
Space and Time Complexity
Time Complexity: O(n^2), where n is the dimension of the square board, since each cell is processed once. Space Complexity: O(n^2) for storing the DP table.
Solution
We solve the problem using dynamic programming. A DP table dp[i][j] is used where each cell stores a tuple representing (maxScore, numPaths) from that position to the target 'E'. The board is processed in reverse order (starting from the bottom-right S) and for each cell we consider the moves allowed: up, left, and diagonal up-left. For each valid move, we update the current cell's dp value:
- If the neighbor's max score is higher than what is currently known, update the current cell with that score plus the current cell’s digit (if applicable) and take the neighbor's path count.
- If the neighbor’s max score equals the best known option, add its path count. Obstacles are skipped in the DP computation. Special consideration is given to the 'E' and 'S' cells where no numeric addition occurs. Finally, if the computed maximum score is negative (or no valid path is found), we return [0, 0].