C++ Simple and Clean Solution (can handle Non-integer Points)


  • 0
    F

    Inner product is all you need. This solution doesn't need any assumption like integer points.
    Here is the main, using my own Vec class (see below)

    class Solution {
    public:
        bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
            Vec va(p1), vb(p2), vc(p3), vd(p4);
            Vec vab = vb - va, vac = vc - va, vad = vd - va, vbc = vc - vb, vbd = vd - vb, vcd = vd - vc;
            if ((vab*vab && vac*vac && vad*vad && vbc*vbc && vbd*vbd && vcd*vcd )== 0)
                return false;
            if (vab * vcd == 0)
                return (vac*vbc || vbc*vbd || vbd*vad || vac*vad) == 0;
            if (vad * vbc == 0)
                return (vac*vcd || vcd*vbd || vbd*vab || vac*vab) == 0;
            if (vac * vbd == 0)
                return (vad*vcd || vcd*vbc || vbc*vab || vad*vab) == 0;
            return false;
        }
    };
    

    This logic can be simplified to one (terrifying) statement:

        bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
            Vec va(p1), vb(p2), vc(p3), vd(p4);
            Vec vab = vb - va, vac = vc - va, vad = vd - va, vbc = vc - vb, vbd = vd - vb, vcd = vd - vc;
            return (vab*vab && vac*vac && vad*vad && vbc*vbc && vbd*vbd && vcd*vcd )!= 0 &&
                (vab * vcd == 0 && (vac*vbc || vbc*vbd || vbd*vad || vac*vad) == 0 ||
                 vad * vbc == 0 && (vac*vcd || vcd*vbd || vbd*vab || vac*vab) == 0 ||
                 vac * vbd == 0 && (vad*vcd || vcd*vbc || vbc*vab || vad*vab) == 0 );
        }
    

    The Vec class is very simple too:

    struct Vec
    {
        int x, y;
        Vec(vector<int> const & vec):x(vec[0]), y(vec[1]){}
        Vec(int _x = 0, int _y = 0):x(_x), y(_y) {}
        long long operator*(Vec to_mult) const
        {
            return x*to_mult.x + y*to_mult.y;
        }
        Vec operator-(Vec to_minus) const
        {
            return {x - to_minus.x, y - to_minus.y};
        }
    };
    

Log in to reply
 

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