Given N points on a 2D plane, find the maximum number of points that lie on the same straight line.
For two points (x1, Y1) and (X2, Y2), the linear equation is: (x1-x2) * Y + (y2-y1) * x + x2 * y1-x1 * y2 = 0, that is: A * Y + B * x + c = 0.
Using the idea similar to breadth-first traversal, Q [I] stores the straight line between the I + 1 vertex and each vertex in the first I vertex, and the number of vertices passing through the straight line in the first I + 1 vertex, Q [I] [0] indicates the number of times that vertex I + 1 has already appeared.
Processing each element of the input sequence in turn, for the current element I, sequentially accessing each Q [k] (k = I-1, I-2 ,..., 0), traverse Q [k] To find the maximum number of vertices in the straight line determined by point I and point K, and save them in Q [I.
In the process of accessing Q [k] from the back, the next value of Q [I] [0] is updated when I and I are duplicated for the first time.
1 class Line 2 { 3 public: 4 Line(): a(0), b(0), c(0), cnt(1) {} 5 ~Line(){} 6 public: 7 int a, b, c; 8 int cnt; 9 };10 11 class Solution {12 public:13 int maxPoints( vector<Point> &points ) {14 if( points.size() <= 2 ) { return points.size(); }15 vector<Line>* Q = new vector<Line>[points.size()];16 Q[0].resize(1);17 int max_num = 2;18 Line optimal;19 for( int i = 1; i < points.size(); ++i ) {20 Q[i].resize(1);21 for( int j = i-1; j >= 0; --j ) {22 optimal.a = points[i].x-points[j].x;23 optimal.b = points[j].y-points[i].y;24 optimal.c = points[j].x*points[i].y-points[i].x*points[j].y;25 if( points[i].x == points[j].x && points[i].y == points[j].y ) {26 if( Q[i][0].cnt == 1 ) { Q[i][0].cnt = Q[j][0].cnt+1; }27 else { continue; }28 optimal.cnt = Q[i][0].cnt;29 for( size_t ID = 1; ID != Q[j].size(); ++ID ) {30 Line& aLine = Q[j][ID];31 if( aLine.a*points[i].y + aLine.b*points[i].x + aLine.c == 0 ) {32 if( optimal.cnt <= aLine.cnt+1 ) { optimal = aLine; ++optimal.cnt; }33 }34 }35 } else {36 optimal.cnt = 2;37 for( size_t ID = 0; ID != Q[j].size(); ++ID ) {38 Line& aLine = Q[j][ID];39 if( aLine.a*points[i].y + aLine.b*points[i].x + aLine.c == 0 ) {40 if( optimal.cnt < aLine.cnt+1 ) { optimal.cnt = aLine.cnt+1; }41 }42 }43 }44 if( max_num < optimal.cnt ) { max_num = optimal.cnt; }45 Q[i].push_back( optimal );46 }47 }48 delete[] Q;49 return max_num;50 }51 };