Squirrel Simulation

Description:

There’s a tree, a squirrel, and several nuts. Positions are represented by the cells in a 2D grid. Your goal is to find the minimal distance for the squirrel to collect all the nuts and put them under the tree one by one. The squirrel can only take at most one nut at one time and can move in four directions - up, down, left and right, to the adjacent cell. The distance is represented by the number of moves.
这里写图片描述

思路:

刚拿到这道题把题目看懂后,不知道如何分析这个问题。第一时间想到的是 BFS和DP,可是不知道如何切入。
这个时候分析问题就要逆向思考,松鼠去找坚果,然后运到树。逆向思考的意思是说,不如让坚果去找树,坚果去找松鼠。
另外假定一些特殊清况,如果松鼠本来就在树那里,那么要做的事情就是,把某个坚果找到并运回,也就是某个坚果到树“距离”的两倍。但是松鼠初始位置不一定在树那,松鼠一旦运好第一个坚果,后面都是从树出发的操作。所以松鼠运第一个坚果的选取,决定了路径的最小值,也就是把某个松鼠–>坚果 替换 坚果 –> 树。

Code:

public class Solution {
    public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) {
        int n = nuts.length;
        int[] nutToTree = new int[n];
        int[] nutToSquirrel = new int[n];

        int sum = 0;
        for (int i = 0; i < n; i++){
            nutToTree[i] = Math.abs(nuts[i][0] - tree[0]) + Math.abs(nuts[i][1] - tree[1]);
            sum += nutToTree[i] * 2;
            nutToSquirrel[i] = Math.abs(nuts[i][0] - squirrel[0]) + Math.abs(nuts[i][1] - squirrel[1]);
        }

        int min = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            int dist = sum + nutToSquirrel[i] - nutToTree[i];
            min = Math.min(min, dist);
        }
        return min;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值