Skip to content

Commit c30ab17

Browse files
authored
Create number-of-paths-with-max-score.cpp
1 parent 03f5a70 commit c30ab17

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Time: O(n^2)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<int> pathsWithMaxScore(vector<string>& board) {
7+
static const int MOD = 1e9 + 7;
8+
static const vector<pair<int, int>> directions{{1, 0}, {0, 1}, {1, 1}};
9+
10+
vector<vector<vector<int>>> dp(2, vector<vector<int>>(board[0].size() + 1, vector<int>(2)));
11+
dp[(board.size() - 1) % 2][board[0].size() - 1] = {0, 1};
12+
for (int r = board.size() - 1; r >= 0; --r) {
13+
for (int c = board[0].size() - 1; c >= 0; --c) {
14+
if (board[r][c] == 'S' || board[r][c] == 'X') {
15+
continue;
16+
}
17+
dp[r % 2][c] = {0, 0};
18+
for (const auto& [dr, dc] : directions) {
19+
if (dp[r % 2][c][0] < dp[(r + dr) % 2][c + dc][0]) {
20+
dp[r % 2][c] = dp[(r + dr) % 2][c + dc];
21+
} else if (dp[r % 2][c][0] == dp[(r + dr) % 2][c + dc][0]) {
22+
dp[r % 2][c][1] = (dp[r % 2][c][1]+dp[(r + dr) % 2][c + dc][1]) % MOD;
23+
}
24+
}
25+
if (dp[r % 2][c][1] && board[r][c] != 'E') {
26+
dp[r % 2][c][0] += board[r][c] - '0';
27+
}
28+
}
29+
}
30+
return dp[0][0];
31+
}
32+
};

0 commit comments

Comments
 (0)