741 Cherry picking

Title: an N x N grid (Grid) represents a cherry, each grid is represented by one of three numbers:
    0 indicates that the grid is empty, so you can pass through it.
    1 indicates that the grid filled with a cherry, then you can pick the cherries through it.
    -1 indicates that the grid has thorns, blocking your way.
Your task is in compliance with the following rules, as far as possible to pick up to Cherry:
    Starting from the position (0, 0), and finally to (N-1, N-1 ), or can only go down to the right, and only through the active grid (i.e., the lattice can only pass through the value of 0 or 1);
    when reaching the (N-1, N-1 ) after you go to continue, until it returns to the (0, 0), only can go up or to the left, and can only be effective through the lattice;
    when you go through a lattice and the lattice contains a cherry, you will pick the cherries and the grid becomes empty (value becomes 0);
    if may pass through a path does not exist between (0, 0), and (N-1, N-1 ), then there is no pick to be a cherry.

Source: https://leetcode-cn.com/problems/cherry-pickup/

Act One: own error code

Idea: to fully analyze the meaning of problems, the original problem are not seeking the maximum two paths following code first seek the maximum path and direction of each record takes maximum path again depending on the direction of the maximum recorded. delete the path, and then seek a second maximum path

from Typing Import List
 class Solution:
     DEF cherryPickup (Self, Grid: List [List [int]]) -> int:
         # required number of rows and columns of 
        R & lt, C = len (Grid), len (Grid [0])
         # The second number is assigned to. 1 
        Grid [0] [0] = (Grid [0] [0], Grid [0] [0], 0)
         # processing a first row and first column, if there is a -1 lattice, it is the latter are set to -1 
        # and recording path, if it is coming from the left is denoted as 1, from the top to the referred to -1 
        # each tuple first recording element and a second record the current original value, the third recording path 
        for I in Range (. 1 , R & lt):
             IF Grid [I] [0] = -1! :
                grid[i][0] = (grid[i][0]+grid[i-1][0][0], grid[i][0], -1)
                continue
            else:
                for j in range(i,r):
                    grid[i][0] = (-1,-1,-1)
            break
        for i in range(1,c):
            if grid[0][i] != -1:
                grid[0][i] = (grid[0][i]+grid[0][i-1][0], grid[0][i],  1)
                continue
            else:
                for j in range(i,c):
                    Grid [0] [I] = (-1, -1,1 )
             BREAK 
        # to find the maximum value of the first path, the path to be recorded 
        for P in Range (. 1 , R & lt):
             for Q in Range (. 1 , C ):
                 IF Grid [P] [Q] == -1 :
                    Grid [P] [Q] = (-1, -1,1 )
                 # first determines whether the grid line inside the thorns 
                elif Grid [. 1-P] [Q] [0] < 0:
                     # if the previous one also has thorns, and assignment put -1 
                    IF Grid [P] [Q-. 1] [0] < 0:
                        grid[p][q] = (-1,-1,1)
                    else:
                        Grid [P] [Q] = (Grid [P] [Q-. 1] [0] + Grid [P] [Q], Grid [P] [Q],. 1 )
                 # on line this time without a grid thorns 
                elif Grid [P] [Q-. 1] [0] < 0:
                     # top and the left of the lattice and has thorns and set to -1 
                    Grid [P] [Q] = (-1, -1,1 )
                 # this when no thorns 
                elif Grid [P] [Q-. 1] [0]> = Grid [P-. 1 ] [Q] [0]:
                     # left large 
                    grid [p] [q] = (grid [p] [ Q-. 1] [0] + Grid [P] [Q], Grid [P] [Q],. 1 )
                 the else :
                     # big top of the 
                    grid [p] [q] = (grid [p-1] [q] [0] + grid [p] [q], grid [p] [q], -1)
        answer1 = Grid [-1] [-. 1 ] [0]
         Print ( ' KK ' , answer1)
         Print (Grid)
         # to remove the first path traversed by the marking made by the maximum, i.e., set to 0 cherry
        m, n = r-1, c-1
        while not grid[0][0][2]:
            Sign = Grid [m] [n-] [2 ]
             # If the note is greater than 0 coming from the left, the column will be reduced. 1 
            IF Sign> 0:
                n- - =. 1 
                Grid [m] [n-] = (0,0, Grid [m] [n-] [2 ])
             # otherwise from the upper side to the 
            elif Sign < 0:
                m - =. 1 
                Grid [m] [n-] = (0,0, Grid [m] [n-] [2 ])
             # otherwise equal to 0, indicating the upper left corner is 
            the else :
                Grid [0] [0] = (0,0,1 )
         # the last grid is set to 0 
        Grid [-1] [-. 1] = (0,0,0)
         Print (Grid)
         # again from the top left to take over the lower right corner 
        for P in Range (. 1 , R & lt):
             for Q in Range (. 1 , C):
                 IF Grid [P] [Q] [. 1] == -1 :
                     Pass 
                # If a front as thorns, is the thorns line will not, or if a condition determined time has a pass out 
                elif Grid [P] [Q-. 1] [. 1] == -1 :
                    grid[p][q] = (grid[p-1][q][0]+grid[p][q][1],grid[p][q][1],grid[p][q][2])
                elif grid[p-1][q][1] == -1:
                    Grid [P] [Q] = (Grid [P] [Q-. 1] [0] + Grid [P] [Q] [. 1], Grid [P] [Q] [. 1], Grid [P] [Q ] [2 ])
                 the else :
                     # Note that this must be added in parentheses in order to ensure at the outermost is a tuple, otherwise is int, 
                    Grid [P] [Q] = (max (Grid [P-. 1] [Q] [0] , Grid [P] [Q-. 1] [0]) + Grid [P] [Q] [. 1], Grid [P] [Q] [. 1], Grid [P] [Q] [2 ])
         return answer1 + grid [-1] [- 1 ] [0]
View Code

Act II: The official dynamic programming method

Thinking: Typical dp dimensional problems, because there are three variables, the most ingenious processing place is the boundary value, the return value of the final end of the tree only two situations, one is -INF, reaching the other (N-1, after N-1) at. unfinished traversal four branches, and returns the maximum recording four branches.

class Solution(object):
    def cherryPickup(self, grid):
        N = len (Grid)
         # for recording input and output values back function. 
        Memo = [[[None] * N for _1 in Range (N)] for _2 in Range (N)]
         DEF DP (R1, C1, c2):
            R2 = R1 + C1 - C2
             # if you encounter brambles, or to go beyond the edge, negative infinity is returned, directly corresponds to the end of this path 
            # here is actually a circle around the edge of thorns 
            if (R1 == N or N == R2 or N == C1 or N == C2 or 
                    Grid [R1] [C1] == -1 or Grid [R2] [C2] == -1 ):
                 return a float ( ' -INF ' )
             # If a grid point to the finish, the other must be the last grid, and return values. 
            # without this condition, the path will come back when (N, N-1) or ( N-1, N) returns '-inf', will return to the final dp -inf, 
            # because -inf numbers are adding any -inf, any condition that has an end point in the path of (N-1 on, N-1) at this point. 
            elifC1 == == N-R1. 1 :
                 # Here will output four values, because of a lattice and B into the final four methods 
                Print (Grid [R1] [C1])
                 return Grid [R1] [C1]
             # if before traversed this value is no longer the back, similar to the function of lru_cache, 
            # when backtracking function encounters the same input value of the second, the return value directly recorded before saving time 
            # Without this condition can also output the correct answer , but times out 
            elif Memo [r1] [c1] [C2] iS  Not None:
                 return Memo [r1] [c1] [C2]
             the else :
                 # if c1 is equal to c2, r1 equals there r2, the two positions coincide, the cherry only be counted once, then c1! = c2 is 0, after multiplied by the number of counted only once cherry 
                # otherwise, if the position does not coincide, then c1! = c2 is true, which requires that the two paths and 
                ans = grid [r1] [c1] + (c1! = c2) *Grid [R2] [C2]
                 # minutes four cases back 
                ANS + = max (DP (R1,. 1 C1 +, C2 +. 1), DP (. 1 + R1, C1, C2 +. 1 ),
                           DP (R1, C1 + 1'd, C2), DP (. 1 + R1 , C1, C2))
             # Each quadtree back number are recorded once finished cherry, and returns the number of path 576 is similar to that community channel a method in question, 
            # purpose is to value given the same input face convenience, direct return value. 
            Memo [R1] [C1] [C2] = ANS
             return ANS
        dp(0,0,0)
        # return max(0, dp(0, 0, 0))
if __name__ == '__main__':
    duixiang = Solution ()
    A = duixiang.cherryPickup ([[1,1,1 ,],
                                 [1,1,1,],
                                 [1,1,1,],
                                ])
    # a = duixiang.cherryPickup( [[1,1,1,1,0,0,0],
    #                             [0,0,0,1,0,0,0],
    #                             [0,0,0,1,0,0,1],
    #                             [1,0,0,1,0,0,0],
    #                             [0,0,0,1,0,0,0],
    #                             [0,0,0,1,0,0,0],
    #                             [0,0,0,1,1,1,1]]
    # )
    print(a)
View Code

ttt

Guess you like

Origin www.cnblogs.com/xxswkl/p/12123822.html