【leetcode】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

解题思路:很显然是动态规划,因为只能往左,上,左上三个方向移动,记dp_val[i][j]为从右下角移动到(i,j)时可以获得的最大值,那么有dp[i][j] = max(dp[i+1][j],dp[i][j+1],dp[i+1][j+1] , 因为还需要求出获得最大值时一共有几种移动路径,记dp_count[i][j]为从右下角移动到(i,j)获得最大值时移动路径的数量,只要相应的三个方向移动到(i,j)时可以得到最大值,那么dp_count[i][j] += dp_counti+x][j+y] 。 此外,还有不能从起点移动到终点的情况,所以在计算之前,可以用DFS/BFS先做一次判断。

代码如下:

class Solution(object):
    def canReach(self,board):
        queue = [(len(board)-1,len(board)-1)]
        dic = {}
        dic[(len(board)-1,len(board)-1)] = 1
        while len(queue) > 0:
            i,j = queue.pop(0)
            if i == 0 and j == 0:
                return True
            direction = [(-1, 0), (0, -1), (-1, -1)]
            for (x, y) in direction:
                if (i + x) >= 0 and (i + x) < len(board) and (j + y) >= 0 and (j + y) < len(board)                         and board[i+x][j+y] != ‘X‘ and (i+x,j+y) not in dic:
                    queue.append((i+x,j+y))
                    dic[(i+x,j+y)] = 1
        return False

    def pathsWithMaxScore(self, board):
        """
        :type board: List[str]
        :rtype: List[int]
        """
        if self.canReach(board) == False:
            return [0,0]
        dp_val = [[0] * len(board) for _ in board]
        dp_count = [[0] * len(board) for _ in board]
        dp_count[-1][-1] = 1

        for i in range(len(board)-1,-1,-1):
            for j in range(len(board)-1,-1,-1):
                if board[i][j] == ‘X‘:continue
                direction = [(1,0),(0,1),(1,1)]
                for (x,y) in direction:
                    if (i + x) >= 0 and (i + x) < len(board) and (j + y) >= 0 and (j + y) < len(board):
                        item_val = 0
                        if board[i+x][j+y] == ‘X‘:
                            continue
                        if board[i][j] != ‘S‘ and board[i][j] != ‘E‘:
                            item_val = int(board[i][j])
                        if dp_val[i][j] < dp_val[i+x][j+y] + item_val:
                            dp_val[i][j] = dp_val[i + x][j + y] + item_val

                for (x,y) in direction:
                    if (i + x) >= 0 and (i + x) < len(board) and (j + y) >= 0 and (j + y) < len(board):
                        item_val = 0
                        if board[i][j] != ‘S‘ and board[i][j] != ‘E‘:
                            item_val = int(board[i][j])
                        if dp_val[i][j] == dp_val[i + x][j + y] + item_val:
                            dp_count[i][j] += dp_count[i + x][j + y]
        return [dp_val[0][0],dp_count[0][0] % (10**9 + 7)]
        

原文地址:https://www.cnblogs.com/seyjs/p/12114161.html

时间: 2024-11-19 13:18:02

【leetcode】1301. 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 w

【LeetCode】Single Number (2 solutions)

Single Number Given an array of integers, every element appears twice except for one. Find that single one. Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 解法一:用map记录每个元素的次数,返回次数为1的元素 cl

【LeetCode】Single Number

原文: Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 解答: 常规解法:先对数组进行排序,然后通过按顺序判断每相邻两个数是否相同即可

【LeetCode】Single Number I &amp; II

Single Number I : Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Solution: 解法不少,贴一种: 1 cla

【LeetCode】Largest Number 解题报告

[题目] Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead of

【LeetCode】Valid Number 解题报告

[题目] Validate if a given string is numeric. Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true Note: It is intended for the problem statement to be ambig

【Leetcode】Guess Number Higher or Lower II

题目链接: 题目: We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number I picked is higher or lower. However, when you guess a

【Leetcode】Happy Number

题目链接:https://leetcode.com/problems/happy-number/ 题目: Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the sq

【LeetCode】257. Binary Tree Paths 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51474128 Subject 出处:https://leetcode.com/problems/binary-tree-paths/ Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / \ 2 3 \ 5 All root-to-le