Erect the Fence | Cross Product Formula | Convex Hull Algorithm | Easy One | With Comments

Upvote if you like the post

class Solution {
public:
    // this function check than c is in clockwise direction when a is at reference point compare to b;
    int clockwise(vector<int>&a,vector<int>&b,vector<int>&c){
        /*
        AC(vector) X AB(vector) > 0 then c(vector) is in clockwise direction 
        | Cx-Ax     Bx-Ax |
        | Cy-Ay     By-Ay |           
            = (Cx-Ax)(By-Ay) - (Cy-Ay)(Bx-Ax)
        
        if (Cx-Ax)(By-Ay) - (Cy-Ay)(Bx-Ax) >  0  then c is clockwise than b;
        */
        
        return ((c[0]-a[0])*(b[1]-a[1]))  - ((c[1]-a[1])*(b[0]-a[0]));
    }
    
    //This function is to check whether i is in between a and b or not
    bool isbetween(vector<int>&a,vector<int>&i,vector<int>&b){
        bool x = (a[0]<=i[0] && i[0]<=b[0]) || (b[0]<=i[0] && i[0]<=a[0]);//for x axis
        bool y = (a[1]<=i[1] && i[1]<=b[1]) || (b[1]<=i[1] && i[1]<=a[1]);//for y axis
        
        return x and y;
    }

    vector<vector<int>> outerTrees(vector<vector<int>>& trees) {
        int n=trees.size();
        if(n<=3)return trees;
        vector<vector<int>>ans;
        
        int leftMostIndex=0;
        for(int i=1;i<n;i++){
            if(trees[i][0]<trees[leftMostIndex][0])
                leftMostIndex=i;
        }
       int a=leftMostIndex; 
       while(true){
           int b=(a+1)%n;// next index after leftMostIndex and modulo so that it does not out of bound
           
           //placing b in the most clockwise direection
           for(int i=0;i<n;i++)
               if(clockwise(trees[a],trees[b],trees[i])>0)b=i;
           
           //Checking is there any collinear between the point b
           for(int i=0;i<n;i++){
               if(i!=a and i!=b and clockwise(trees[a],trees[b],trees[i])==0 and isbetween(trees[a],trees[i],trees[b]))
                   ans.push_back(trees[i]);
           }
           ans.push_back(trees[b]);
           a=b;
           if(a==leftMostIndex)break;
           
       } 
        //remove duplicate;
        sort(ans.begin(),ans.end());
        ans.erase(unique(ans.begin(),ans.end()),ans.end());
        return ans;
    }
};
Comments (0)