C# Solution O(n) space


  • 0
    J
    public int MinDistance1(int height, int width, int[] tree, int[] squirrel, int[,] nuts)
    {
        int tot = 0;
        var tDis = new int[nuts.GetLength(0)];
        var sDis = new int[nuts.GetLength(0)];
    
        for (var i = 0; i < nuts.GetLength(0); i++) {
           tDis[i] = GetDistance(tree[0], tree[1], nuts[i, 0], nuts[i, 1]);
           sDis[i] = GetDistance(squirrel[0], squirrel[1], nuts[i, 0], nuts[i, 1]);
    
           tot += tDis[i] * 2;
        }
    
       int min = Int32.MaxValue;           
       for (var i = 0; i < nuts.GetLength(0); i++) min = Math.Min(min, tot - tDis[i] + sDis[i]);
    
       return min;
    }
    
    private int GetDistance(int x1, int y1, int x2, int y2)
    {
        return Math.Abs(x2 - x1) + Math.Abs(y2 - y1);
    }

Log in to reply
 

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