首页 > 其他分享 >741. Cherry Pickup (Hard)

741. Cherry Pickup (Hard)

时间:2023-06-21 17:55:45浏览次数:43  
标签:741 Hard up Pickup cherries grid x2 x1 dp

Description

741. Cherry Pickup (Hard)

You are given an n x n grid representing a field of cherries, each cell is one of three possible integers.

  • 0 means the cell is empty, so you can pass through,
  • 1 means the cell contains a cherry that you can pick up and pass through, or
  • -1 means the cell contains a thorn that blocks your way.

Return the maximum number of cherries you can collect by following the rules below:

  • Starting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with value 0 or 1).
  • After reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells.
  • When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell 0.
  • If there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected.

 

Example 1:

Input: grid = [[0,1,-1],[1,0,-1],[1,1,1]]
Output: 5
Explanation: The player started at (0, 0) and went down, down, right right to reach
(2, 2).
4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].
Then, the player went left, up, up, left to return home, picking up one more cherry.
The total number of cherries picked up is 5, and this is the maximum possible.

Example 2:

Input: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]
Output: 0

 

Constraints:

  • n == grid.length
  • n == grid[i].length
  • 1 <= n <= 50
  • grid[i][j] is -1, 0, or 1.
  • grid[0][0] != -1
  • grid[n - 1][n - 1] != -1

Solution

This problem can be approached using dynamic programming, and although the concept is straightforward, there are several details to consider.

The process of picking cherries back and forth is equivalent to two individuals moving from $[0, 0]$ to $[n - 1, n - 1]$.

Let's use $k$ to represent the number of steps taken, $x_1$ to represent the current $x$ coordinate of the first person, and $x_2$ to represent the current $x$ coordinate of the second person. The current coordinates of the first and second persons can be calculated as $k - x_1$ and $k - x_2$, respectively.

$dp[k][x_1][x_2]$ represents the total number of cherries picked by the two persons after taking $k$ steps, with the first person at position $(x_1, k - x_1)$ and the second person at position $(x_2, k - x_2)$.

The state $(k, x_1, x_2)$ can be reached from four possible previous states: $(k - 1, x_1 - 1, x_2)$, $(k - 1, x_1 - 1, x_2 - 1)$, $(k - 1, x_1, x_2)$, and $(k - 1, x_1, x_2 - 1)$. Based on this, we can establish the following recurrence relation:

  • If $x_1 = x_2$, then $dp[k][x_1][x_2] = dp[k - 1][prex_1][prex_2] + grid[x_1][y_1]$.
  • Otherwise, $dp[k][x_1][x_2] = dp[k - 1][prex_1][prex_2] + grid[x_1][y_1] + grid[x_2][y_2]$.

$dp[k - 1][prex_1][prex_2]$ represents the maximum value among the four possible previous states. It's important to note that if a thorny bush is encountered, $dp[k][x_1][x_2]$ should be set to $-\infty$ instead of $0$ to indicate that the path is impassable.

Code

class Solution {
  public:
    int cherryPickup(vector<vector<int>> &grid) {
        int n = grid.size();
        vector<vector<vector<int>>> dp(2 * n + 1, vector<vector<int>>(n, vector<int>(n, INT_MIN)));
        vector<vector<int>> mov{{-1, 0}, {-1, -1}, {0, -1}, {0, 0}};
        dp[0][0][0] = grid[0][0];
        for (int i = 1; i <= 2 * n - 2; ++i) {
            for (int x1 = 0; x1 <= i && x1 < n; ++x1) {
                for (int x2 = 0; x2 <= x1 && x2 < n; ++x2) {
                    int y1 = i - x1, y2 = i - x2;
                    if (y1 < 0 || y1 >= n || y2 < 0 || y2 >= n) {
                        continue;
                    }
                    if (grid[x1][i - x1] == -1 || grid[x2][i - x2] == -1) {
                        dp[i][x1][x2] = INT_MIN;
                        continue;
                    }
                    int tmp = INT_MIN; // tmp must be -infty
                    for (int j = 0; j < 4; ++j) {
                        int prex1 = x1 + mov[j][0], prey1 = i - 1 - prex1;
                        int prex2 = x2 + mov[j][1], prey2 = i - 1 - prex2;
                        if (prex1 < 0 || prex1 >= n || prey1 < 0 || prey1 >= n || prex2 < 0 || prex2 >= n || prey2 < 0 || prey2 >= n) {
                            continue;
                        }
                        if (grid[prex1][prey1] == -1 || grid[prex2][prey2] == -1) {
                            continue;
                        }
                        tmp = max(tmp, dp[i - 1][prex1][prex2]);
                    }
                    if (x1 == x2) {
                        dp[i][x1][x2] = max(dp[i][x1][x2], tmp + grid[x1][i - x1]);
                    } else {
                        dp[i][x1][x2] = max(dp[i][x1][x2], tmp + grid[x1][i - x1] + grid[x2][i - x2]);
                    }
                }
            }
        }
        return max(dp[2 * n - 2][n - 1][n - 1], 0);
    }
};

标签:741,Hard,up,Pickup,cherries,grid,x2,x1,dp
From: https://www.cnblogs.com/zwyyy456/p/17496838.html

相关文章

  • 1595. 连通两组点的最小成本 (Hard)
    问题描述1595.连通两组点的最小成本(Hard)给你两组点,其中第一组中有size₁个点,第二组中有size₂个点,且size₁>=size₂。任意两点间的连接成本cost由大小为size₁xsize₂矩阵给出,其中cost[i][j]是第一组中的点i和第二组中的点j的连接成本。如果两个组中......
  • 1595. Minimum Cost to Connect Two Groups of Points] (Hard)
    Description1595.MinimumCosttoConnectTwoGroupsofPoints(Hard)Youaregiventwogroupsofpointswherethefirstgrouphassize1points,thesecondgrouphassize2points,andsize1>=size2.Thecostoftheconnectionbetweenanytwopointsar......
  • CF958C3. Encryption (hard)
    谁说\(n\le5\times10^5\),\(k\le100\),\(p\le100\)只能\(O(nk)\)?我今天就要用\(O(nk\logp)\)过这个题!定义\(f_{i,j}\)表示前\(j\)个数,分成\(i\)段的最小价值和,\(s_i\)表示前缀和(对\(p\)取模),转移就是\(f_{i,j}=\min\limits_{l=1}^{j-1}\left\{f_{i-1,l}+\left(s_......
  • Docker配置SpringBoot+ShardingJDBC+MybatisPlus项目实现分库分表与读写分离
    Docker配置SpringBoot+ShardingJDBC+MybatisPlus项目实现分库分表与读写分离 分类于 实战例子本文ShardingJDBC相关知识主要参考自ShardingJDBC官方文档,更多的用法建议到官网文档查看。前言传统的业务系统都是将数据集中存储至单一数据节点的解决方案,如今随着互联网数据......
  • 1494. 并行课程 II (Hard)
    问题描述1494.并行课程II(Hard)给你一个整数n表示某所大学里课程的数目,编号为1到n,数组relations中,relations[i]=[xᵢ,yᵢ]表示一个先修课的关系,也就是课程xᵢ必须在课程yᵢ之前上。同时你还有一个整数k。在一个学期中,你最多可以同时上k门课,前提是这......
  • 1494. Parallel Courses II (Hard)
    Description1494.ParallelCoursesII(Hard)Youaregivenanintegern,whichindicatesthattherearencourseslabeledfrom1ton.Youarealsogivenanarrayrelationswhererelations[i]=[prevCoursei,nextCoursei],representingaprerequisiterelat......
  • 552.Student Attendance Record II (Hard)
    Description552.StudentAttendanceRecordII(Hard)Anattendancerecordforastudentcanberepresentedasastringwhereeachcharactersignifieswhetherthestudentwasabsent,late,orpresentonthatday.Therecordonlycontainsthefollowingthre......
  • 1483. Kth Ancestor of a Tree Node (Hard)
    Description1483.KthAncestorofaTreeNode(Hard)Youaregivenatreewithnnodesnumberedfrom0ton-1intheformofaparentarrayparentwhereparent[i]istheparentofithnode.Therootofthetreeisnode0.Findthekthancestorofagive......
  • 智能合约HardHat框架环境的搭建
    1.首先创建一个npm项目PSC:\Users\lcds\blockchainprojects>mkdirhardhatcontractPSC:\Users\lcds\blockchainprojects>cd.\hardhatcontract\2.运行 npminit-y  初始化项目PSC:\Users\lcds\blockchainprojects\hardhatcontract>npminit-yWrotetoC:\......
  • [ABC162E] Sum of gcd of Tuples (Hard)
    题面翻译给定\(n,k\),求\[\sum^k_{a_1=1}\sum^k_{a_2=1}\sum^k_{a_3=1}\dots\sum^k_{a_n=1}gcd(a_1,a_2,a_3,\dots,a_n)\mod\1000000007\]制約$2\\leq\N\\leq\10^5$$1\\leq\K\\leq\10^5$。思路点拨我们看到这么多\(\gcd\)的式子,我们自然想到莫比乌斯反演......