【LeetCode1301】 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();
        vector<vector<int> > dp(n+1, vector<int>(n+1, 0));
        vector<vector<int> > path(n+1, vector<int>(n+1, 0));
        path[n-1][n-1] = 1;
        board[n-1][n-1] = '0';
        board[0][0] = '0';
        int mod = 1e9 + 7;
        
        for (int i=n-1; i>=0; --i) {
            for (int j=n-1; j>=0; --j) {
                if (board[i][j] == 'X') continue;
                int m = max(max(dp[i+1][j], dp[i][j+1]), dp[i+1][j+1]);
                dp[i][j] = (board[i][j] - '0') + m;
                if (m == dp[i+1][j]) path[i][j] = (path[i][j] + path[i+1][j]) % mod;
                if (m == dp[i][j+1]) path[i][j] = (path[i][j] + path[i][j+1]) % mod;
                if (m == dp[i+1][j+1]) path[i][j] = (path[i][j] + path[i+1][j+1]) % mod;
            }
        }
        
        return {path[0][0] ? dp[0][0] : 0, path[0][0]};
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值