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

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`

``````class Solution {
public:
vector<int> pathsWithMaxScore(vector<string>& board) {
int n = board.size(), M = 1e9 + 7;
vector<vector<int>> score(n, vector<int>(n)), path = score;
vector<vector<int>> dirs{{0, -1}, {-1, 0}, {-1, -1}};
path[n - 1][n - 1] = 1;
for (int i = n - 1; i >= 0; --i) {
for (int j = n - 1; j >= 0; --j) {
if (path[i][j] == 0) continue;
for (auto dir : dirs) {
int x = i + dir[0], y = j + dir[1];
if (x < 0 || y < 0 || board[x][y] == 'X') continue;
int sum = score[i][j];
if (board[x][y] != 'E') sum += board[x][y] - '0';
if (sum > score[x][y]) {
score[x][y] = sum;
path[x][y] = path[i][j];
} else if (sum == score[x][y]) {
path[x][y] = (path[x][y] + path[i][j]) % M;
}
}
}
}
return {score[0][0], path[0][0]};
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1301

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

https://leetcode.com/problems/number-of-paths-with-max-score/discuss/463539/C%2B%2B-DP

https://leetcode.com/problems/number-of-paths-with-max-score/discuss/463196/Java-DP-Solution-Clean-code-O(m*n)

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation