LWC 61:741. Cherry Pickup

LWC 61:741. Cherry Pickup

传送门:741. Cherry Pickup

Problem:

In a 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; -1 means the cell contains a thorn that blocks your way. Your task is to collect maximum number of cherries possible 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.

Note:

Grid is an N by N 2D array, with 1 <= N <= 50.

Each grid[i][j] is an integer in the set {-1, 0, 1}.

It is guaranteed that grid[0][0] and grid[N-1][N-1] are not -1.

思路: 先出再回来。实际上可以看作两条出发的线抵达N-1即可。此处的trick在于被选择后的状态该如何记录。实际上如果去的时候两条路线重合的话只会加一次cherry。此题采用递归+记忆化的手段,当然因为借鉴了别人的思路,所以具体的解题演变过程在此处就无法展示了。在代码中列举一些自己的comment吧。

Java版本:

    public int cherryPickup(int[][] grid) {
        n = grid.length;
        m = grid[0].length;

        v = new int[n][m];

        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                v[i][j] = grid[i][j];
            }
        }

        mem = new int[52][52][52];
        for (int i = 0; i < 52; ++i) {
            for (int j = 0; j < 52; ++j) {
                for (int k = 0; k < 52; ++k) {
                    mem[i][j][k] = -1;
                }
            }
        }

        // grid[0][0] 始终会被访问到,f在求解问题时,是从起点出发(不包含起点)的最大cherry数
        int ans = f(0, 0, 0, 0) + grid[0][0];
        return ans < -10000 ? 0 : ans;
    }

    int[][] v;
    int n, m;
    int INF = 0x3f3f3f3f;

    int[][][] mem;

    int[] dx = {1, 0};
    int[] dy = {0, 1};
    int f(int x1, int y1, int x2, int y2) {
        // 一旦抵达终态则范围0, 因为此处f的最大cherry数不包含起点,所以终态才为 (n - 1, m - 1)
        if (x1 == n - 1 && y1 == m - 1) return 0;
        // x2一旦确定,y2跟着确定,没必要记录y2的状态
        if (mem[x1][y1][x2] != -1) return mem[x1][y1][x2];
        int ans = -INF;

        for (int i = 0; i < 2; ++i) {
            for (int j = 0; j < 2; ++j) {
                // 只能往右 和 往下
                int nx1 = x1 + dx[i];
                int ny1 = y1 + dy[i];

                int nx2 = x2 + dx[j];
                int ny2 = y2 + dy[j];

                if (nx1 >= 0 && nx1 < n && nx2 >= 0 && nx2 < n && ny1 >= 0 && ny1 < m && ny2 >= 0 && ny2 < m) {
                    if (v[nx1][ny1] == -1) continue;
                    if (v[nx2][ny2] == -1) continue;

                    if (nx1 == nx2 && ny1 == ny2) {
                        // 重合的情况,只需加一次cherry,第一次取cherry,第二次经过但无cherry可取
                        ans = Math.max(ans, v[nx1][ny1] + f(nx1, ny1, nx2, ny2));
                    }
                    else {
                        // 去取一次cherry,回也取一次cherry
                        ans = Math.max(ans, v[nx1][ny1] + v[nx2][ny2] + f(nx1, ny1, nx2, ny2));
                    }
                }
            }
        }
        return mem[x1][y1][x2] = ans;
    }

Python 版本:(超时)

    def cherryPickup(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        n = len(grid)
        m = len(grid[0])

        dp = dict()
        dx = [1, 0]
        dy = [0, 1]

        INF = 0x3f3f3f3f;

        def f(x1, y1, x2, y2):
            if (x1 == n - 1 and y1 == m - 1): return 0
            if ((x1, y1, x2) in dp): return dp[(x1, y1, x2)]

            ans = -INF
            for i in range(2):
                for j in range(2):
                    nx1 = x1 + dx[i]
                    ny1 = y1 + dy[i]

                    nx2 = x2 + dx[j]
                    ny2 = y2 + dy[j]

                    if (nx1 >= 0 and nx1 < n and ny1 >= 0 and ny1 < m and nx2 >= 0 and nx2 < n and ny2 >= 0 and ny2 < m):
                        if (grid[nx1][ny1] == -1): continue
                        if (grid[nx2][ny2] == -1): continue

                        if (nx1 == nx2 and ny1 == ny2):
                            ans = max(ans, grid[nx1][ny1] + f(nx1, ny1, nx2, ny2))
                        else:
                            ans = max(ans, grid[nx1][ny1] + grid[nx2][ny2] + f(nx1, ny1, nx2, ny2))

            dp[(x1, y1, x2)] = ans
            return ans

        ans = f(0, 0, 0, 0) + grid[0][0]
        if ans < -10000: return 0
        return ans        

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏LeetCode

LeetCode <dp>62&63.Unique Paths I&II

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the...

1184
来自专栏小樱的经验随笔

Codeforces Round #411 (Div. 2)(A,B,C,D 四水题)

A. Fake NP time limit per test:1 second memory limit per test:256 megabytes inpu...

2776
来自专栏Bingo的深度学习杂货店

Q62 Unique Paths

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the...

922
来自专栏数据结构与算法

洛谷P1762 偶数(找规律)

 https://www.luogu.org/problemnew/solution/P1762 Orz

532
来自专栏WindCoder

Discuz数据库security_failedlog错误及修复

最近跑了之前的论坛转了转,发现一直在报数据库中表security_failedlog错误,百度了好久,最终找到解决方案。

1231
来自专栏wym

图的割点 --《啊哈!算法》

   这个算法的关键在于:当深度优先遍历访问到顶点u时,假设图中还有顶点v是没有访问过的点,如何判断顶点v在不经过u

1092
来自专栏Hadoop实操

Hue中无法删除用户异常分析

温馨提示:要看高清无码套图,请使用手机打开并单击图片放大查看。 Fayson的github:https://github.com/fayson/cdhproje...

39013
来自专栏C语言及其他语言

[蓝桥杯]Hello, world!

题目描述 This is the first problem for test. Since all we know the ASCII code, your ...

3308
来自专栏小樱的经验随笔

UVa 11461 - Square Numbers【数学,暴力】

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=...

3055
来自专栏小樱的经验随笔

NYOJ 题目77 开灯问题(简单模拟)

开灯问题 时间限制:3000 ms  |            内存限制:65535 KB 难度:1 描述 有n盏灯,编号为1~n,第1个人把所有灯打开,第2个...

2657

扫码关注云+社区