[LeetCode] Number of Paths with Max Score

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

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
class Solution {
public:
vector<int> pathsWithMaxScore(vector<string>& board) {
int n = board.size(), m = board[0].size(), mod = 1e9 + 7;
vector<vector<pair<int, int>>> dp(n, vector<pair<int,int>>(m, {0,0}));
dp[0][0] = {0,1};
for(int i = 1; i < m and board[0][i] != 'X'; i++) {
dp[0][i] = {(dp[0][i-1].first + (board[0][i] & 0b1111)) % mod, 1};
}
for(int i = 1; i < n and board[i][0] != 'X'; i++) {
dp[i][0] = {(dp[i-1][0].first + (board[i][0] & 0b1111)) % mod, 1};
}
for(int i = 1; i < n; i++) {
for(int j = 1; j < m; j++) {
if('1' <= board[i][j] and board[i][j] <= '9') {
int first = max({dp[i-1][j].first, dp[i][j-1].first, dp[i-1][j-1].first});
int second = (dp[i-1][j].first == first ? dp[i-1][j].second : 0) + (dp[i][j-1].first == first ? dp[i][j-1].second : 0) + (dp[i-1][j-1].first == first ? dp[i-1][j-1].second : 0);
if(second) dp[i][j] = {((board[i][j] & 0b1111) + first) % mod, second % mod};
} else if(board[i][j] == 'S') {
int first = max({dp[i-1][j].first, dp[i][j-1].first, dp[i-1][j-1].first});
int second = (dp[i-1][j].first == first ? dp[i-1][j].second : 0) + (dp[i][j-1].first == first ? dp[i][j-1].second : 0) + (dp[i-1][j-1].first == first ? dp[i-1][j-1].second : 0);
if(second) dp[i][j] = {first, second};
}
}
}
return {dp[n-1][m-1].first % mod, dp[n-1][m-1].second % mod};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/01/PS/LeetCode/number-of-paths-with-max-score/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.