741. cherry picking

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 the most cherries:

  • Starting from the position (0, 0), and finally to (N-1, N-1), can only go down or right and can only be effective through the lattice (i.e., the lattice can only pass through the value 0 or 1, );
  • When reaching the (N-1, N-1) after you go to continue, until it returns to the (0, 0), can go up or to the left, and only through the effective lattice;
  • When you pass through the grid comprises a grid and a cherry, you pick the cherries and this grid becomes empty (the value becomes 0);
  • If (0, 0), and (N-1, N-1) may be a path does not exist between passes, then there is no pick to be a cherry.

Example 1:

输入: grid =
[[0, 1, -1],
 [1, 0, -1],
 [1, 1,  1]]
输出: 5
解释: 
玩家从(0,0)点出发,经过了向下走,向下走,向右走,向右走,到达了点(2, 2)。
在这趟单程中,总共摘到了4颗樱桃,矩阵变成了[[0,1,-1],[0,0,-1],[0,0,0]]。
接着,这名玩家向左走,向上走,向上走,向左走,返回了起始点,又摘到了1颗樱桃。
在旅程中,总共摘到了5颗樱桃,这是可以摘到的最大值了。

Description:

  • gridN* Ntwo-dimensional array, N is ranges 1 <= N <= 50.
  • Each  grid[i][j]is a collection of  {-1, 0, 1}a number of them.
  • We can guarantee the start  grid[0][0] and end  grid[N-1][N-1] values will not be -1.

Guess you like

Origin blog.csdn.net/umbrellasoft/article/details/90376514