leetcode 1301 - Number of Paths with Max Score

https://leetcode.com/problems/number-of-paths-with-max-score/

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
vector<int> pathsWithMaxScore(vector<string>& board) {
int mod = 1e9 + 7;
vector<vector<int>> dirs = {{0,-1},{-1,0},{-1,-1}};

int row = board.size(), col = board[0].size();

vector<vector<pair<int,int>>> dp(row, vector<pair<int,int>>(col, {0, 0}));
dp[0][0] = {0, 1};

for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (i == 0 && j == 0) continue;
if (board[i][j] == 'X') continue;

for (auto &dir : dirs) {
int x = i + dir[0], y = j + dir[1];
if (x < 0 || x >= row || y < 0 || y >= col || board[x][y] == 'X') continue;

if (dp[x][y].first > dp[i][j].first)
dp[i][j] = dp[x][y];
else if (dp[x][y].first == dp[i][j].first)
dp[i][j].second = (dp[i][j].second + dp[x][y].second) % mod;
}

if (i != row - 1 || j != col - 1)
dp[i][j].first += board[i][j] - '0';

dp[i][j].first %= mod;
}
}

auto &p = dp[row-1][col-1];
if (p.second == 0)
return vector<int>{0,0};
return vector<int>{p.first, p.second};
}
};