// C# implemenataion of the above approach
using System;
using System.Collections.Generic;
// Defining a class to implement Equals and GetHashCode
// methods for int[] as key
public class MyEqualityComparer : IEqualityComparer<int[]>
{
// This method compares two int[] arrays
public bool Equals(int[] x, int[] y)
{
if (x.Length != y.Length)
{
return false;
}
for (int i = 0; i < x.Length; i++)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
// This method generates a hashcode for an int[] key
public int GetHashCode(int[] obj)
{
int result = 17;
for (int i = 0; i < obj.Length; i++)
{
unchecked
{
result = result * 23 + obj[i];
}
}
return result;
}
}
class GFG
{
// find the largest square
static void findLargestSquare(int[,] points, int n)
{
// map to store which points exist
Dictionary<int[], int> m = new Dictionary<int[], int>(new MyEqualityComparer());
// mark the available points
for (int i = 0; i < n; i++) {
int[] l1 = {points[i, 0], points[i, 1]};
if (!m.ContainsKey(l1))
m[l1] = 0;
m[l1]++;
}
int side = -1, x = -1, y = -1;
// a nested loop to choose the opposite corners of square
for (int i = 0; i < n; i++) {
// remove the chosen point
int[] l1= {points[i, 0], points[i, 1]};
m[l1]--;
for (int j = 0; j < n; j++) {
int[] l2 = {points[j,0], points[j,1]};
// remove the chosen point
m[l2]--;
int[] l3 = {points[i,0], points[j,1]};
int[] l4 = {points[j,0], points[i,1]};
// check if the other two points exist
if (i != j
&& (points[i,0]-points[j,0]) == (points[i,1]-points[j,1])){
if (m.ContainsKey(l3)
&& m.ContainsKey(l4)) {
// if the square is largest then store it
if (side < Math.Abs(points[i,0] - points[j,0])
|| (side == Math.Abs(points[i,0] - points[j,0])
&& ((points[i,0] * points[i,0]
+ points[i,1] * points[i,1])
< (x * x + y * y)))) {
x = points[i,0];
y = points[i,1];
side = Math.Abs(points[i,0] - points[j,0]);
}
}
}
// add the removed point
m[l2]++;
}
// add the removed point
m[l1]++;
}
// display the largest square
if (side != -1)
Console.WriteLine("Side of the square is : " + side +
", \npoints of the square are " + x + ", " + y
+ " "
+ (x + side) + ", " + y
+ " "
+ (x) + ", " + (y + side)
+ " "
+ (x + side) + ", " + (y + side));
else
Console.WriteLine("No such square");
}
//Driver code
public static void Main(string[] args)
{
int n = 6;
// given points
int[,] points = { { 1, 1 }, { 4, 4 }, { 3, 4 }, { 4, 3 }, { 1, 4 }, { 4, 1 } };
// find the largest square
findLargestSquare(points, n);
}
}
// This code is contributed by phasing17