A simple solution is to check if the determinant of the three points selected is non-zero or not. The following determinant gives the area of a Triangle (Also known as Cramer’s rule). Area of the triangle with corners at (x1, y1), (x2, y2) and (x3, y3) is given by:
We can solve this by taking all possible combination of 3 points and finding the determinant.
// C++ program to count number of triangles that can
// be formed with given points in 2D
// A point in 2D
// Returns determinant value of three points in 2D
Auxiliary Space: O(1) because it is using constant space
Optimization : We can optimize the above solution to work in O(n2) using the fact that three points cannot form a triangle if they are collinear. We can use hashing to store slopes of all pairs and find all triangles in O(n2) time. This article is contributed by Vrushank Upadhyay. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...