Leetcode 741 Cherry Pickup

http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-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.

题目大意:给你樱桃田的地图(1: 樱桃, 0: 空, -1: 障碍物)。然你从左上角走到右下角(只能往右或往下),再从右下角走回左上角(只能往左或者往上)。问你最多能采到多少棵樱桃。

思路:

动态规划

关键点: 从(0,0) 到 (n-1, n-1) 再回到 (0, 0) 相当于两次从 (n-1,n-1) 到 (0,0)

  1. 想象有两个人从(n-1, n-1) 到(0, 0).
  2. 两人同时(向左或向上)移动一格,当格子上有草莓时将其捡起.
  3. 如果两人移动到同一个格子,并且格子上有草莓时,仅有一人能捡到草莓.

方案: DP / Recursion with memoization.

dp(x1, y1, x2,y2) 表示从两个人分别从(x1, y1), (x2, y2) 到(0,0)捡到的最大草莓数。

因为两个人同时从同一点出发,其移动的步数相同,即 x1+y1 =x2 + y2 => y2 = x1+y1-x2, 那么dp(x1,y1,x2,y2)可以由dp(x1,y1,x2)来表示。



class Solution {
    private int[][][] m_;
    public int cherryPickup(int[][] grid) {
        int N = grid.length;
        m_ = new int[N][N][N];
        for(int i = 0; i < N; i++){
            for(int j =0; j < N; j++){
                for(int k = 0; k < N; k++){
                    m_[i][j][k] = Integer.MIN_VALUE;
                }
            }
        }
       
       return Math.max(0, dp(N-1, N-1, N-1, grid));   
       
    }
    private int dp(int x1, int y1, int x2, int[][] grid){
        int y2 = x1 + y1 - x2;
        if(x1 < 0 || y1 < 0 || x2 < 0 || y2 < 0) return -1;
        if(grid[y1][x1] < 0 || grid[y2][x2] < 0) return -1;
        if (x1 == 0 && y1 == 0) return grid[y1][x1];
        if (m_[x1][y1][x2] != Integer.MIN_VALUE) return m_[x1][y1][x2];        
        int ans =  Math.max(Math.max(dp(x1-1, y1, x2-1, grid), dp(x1, y1-1, x2, grid)),
                       Math.max(dp(x1, y1-1, x2-1, grid), dp(x1-1, y1, x2, grid)));
        if (ans < 0) {
            m_[x1][y1][x2] = -1;
            return m_[x1][y1][x2];
        }
        ans += grid[y1][x1];
        if (x1 != x2) ans += grid[y2][x2];
        
        m_[x1][y1][x2] = ans;
        return ans;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值