Given n points in a plane , how many squares can be formed ...??
I tried this by calculating the distances between each 2 points , then sort them , and look for the squares in the points with four or more equal distances after verifying the points and slopes.
But this looks like an approach with very high complexity . Any other ideas ...??
I thought dynamic programming for checking for line segments of equal distances might work ... but could not get the idea quite right ....
Any better ideas???
P.S : The squares can be in any manner . They can overlap , have a common side, one square inside another ...
If possible please give a sample code to perform the above...
Approach: The idea is to pick any point and calculate its distance from the rest of the points. Let the picked point be 'p'. To form a square, the distance of two points must be the same from 'p', let this distance be d. The distance from one point must be different from that d and must be equal to √2 times d.
For formation of maximum number of squares, 6 lines must be horizontal and parallel to each other and 6 must be vertical i.e., a square must be formed of 6 lines horizontal and 6 vertical as shown below. Hence, the maximum possible number of squares that can be formed using 12 straight lines is 55.
We need to find the number of rectangles which are not squares, for that we will subtract the number of squares from the number of rectangles to get the required number of rectangles. is the number of columns. Number of squares in a grid =m×n+(m−1)(n−1)+(m−2)(n−2)+(m−3)(n−3.
Let d[i][j] = distances between points i and j
. We are interested in a function count(i, j)
that returns, as fast as possible, the number of squares that we can draw by using points i
and j
.
Basically, count(i, j)
will have to find two points x
and y
such that d[i][j] = d[x][y]
and check if these 4 points really define a square.
You can use a hash table to solve the problem in O(n^2)
on average. Let H[x] = list of all points (p, q) that have d[p][q] = x
.
Now, for each pair of points (i, j)
, count(i, j)
will have to iterate H[ d[i][j] ]
and count the points in that list that form a square with points i
and j
.
This should run very fast in practice, and I don't think it can ever get worse than O(n^3)
(I'm not even sure it can ever get that bad).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With