Java easy to understand(comments included)


  • 0
    public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) {
            int sum=0;
            int n=nuts.length;
            int[] nTotree=new int[n];
            int[] sTon=new int[n];
     // we count the total length from each nut to the tree,
    // *2 means the round trip
            for(int i=0;i<n;i++){
                nTotree[i]=countDistance(nuts[i],tree);
                sum+=nTotree[i]*2;
                sTon[i]=countDistance(squirrel,nuts[i]);
            }
            int min=Integer.MAX_VALUE;
    //Let the sum minus the route from nut to tree and plus squirrel to nut
    // get the minimum length
            for(int i=0;i<n;i++){
                int dis=sum-nTotree[i]+sTon[i];
                min=Math.min(dis,min);
            }
            return min;
        }
    // counting the Manhattan distance
        public int countDistance(int[] pos1,int[] pos2){
            int disX=Math.abs(pos1[0]-pos2[0]);
            int disY=Math.abs(pos1[1]-pos2[1]);
            return disX+disY;
            
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.