Last active
June 20, 2020 22:12
-
-
Save oshea00/e05e49b6a7a592cfcc0f3ef812dd84c4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var p1 = new List<(int x, int y)> { | |
(1,1), (1,3), (3,1), (3,3), (2,2) | |
}; | |
var p2 = new List<(int x, int y)> { | |
(1,1), (1,3), (3,1), (3,3), (4,1), (4,3) | |
}; | |
var p3 = new List<(int x, int y)> { | |
(1,1), (1,4), (2,3), (3,1), (3,2), (3,3), (4,2), (4,3), (5,2) | |
}; | |
var p4 = new List<(int x, int y)> { | |
(1,3), (2,1), (2,0), (4,3), (0,4), (4,2), (1,0), (3,4), (2,4), (4,0) | |
}; | |
var p5 = new List<(int x, int y)> { | |
(1,1),(1,3),(3,1),(3,3),(4,1),(4,3) | |
}; | |
var p6 = new List<(int x, int y)> { | |
(0,1),(3,2),(0,0),(4,4),(2,0),(1,3),(0,4),(4,2),(1,0),(2,4) | |
}; | |
var p = new Solution(); | |
(p.MinAreaRect(Solution.Points(p1)) == 4).Dump(); | |
(p.MinAreaRect(Solution.Points(p2)) == 2).Dump(); | |
(p.MinAreaRect(Solution.Points(p3)) == 1).Dump(); | |
(p.MinAreaRect(Solution.Points(p4)) == 9).Dump(); | |
(p.MinAreaRect(Solution.Points(p5)) == 2).Dump(); | |
(p.MinAreaRect(Solution.Points(p6)) == 8).Dump(); | |
} | |
public class Solution | |
{ | |
public static int[][] Points(List<(int x, int y)> pts) | |
{ | |
int n = 0; | |
var p = new int[pts.Count][]; | |
foreach (var pt in pts) | |
{ | |
if (p[n] is null) | |
p[n] = new int[2]; | |
p[n][0] = pt.x; | |
p[n][1] = pt.y; | |
n++; | |
} | |
return p; | |
} | |
public int MinAreaRect(int[][] points) | |
{ | |
const int X = 0; | |
const int Y = 1; | |
int minArea = int.MaxValue; | |
var grid = new SparseGrid(points); | |
for (int i = 0; i < points.Length - 1; i++) | |
{ | |
for (int j = i + 1; j < points.Length; j++) | |
{ | |
var p1x = points[i][X]; | |
var p1y = points[i][Y]; | |
var p2x = points[j][X]; | |
var p2y = points[j][Y]; | |
var provisionalArea = Math.Abs((p1x - p2x) * (p1y - p2y)); | |
if (provisionalArea == 0 || provisionalArea >= minArea) | |
continue; | |
if (grid.Exists(p1x, p2y) && grid.Exists(p2x, p1y)) | |
minArea = Math.Min(provisionalArea, minArea); | |
} | |
} | |
return minArea == int.MaxValue ? 0 : minArea; | |
} | |
} | |
public class SparseGrid | |
{ | |
Dictionary<int, Dictionary<int, int>> grid; | |
public SparseGrid() | |
{ | |
grid = new Dictionary<int, Dictionary<int, int>>(); | |
} | |
public SparseGrid(int[][] points) : this() | |
{ | |
foreach (var p in points) | |
{ | |
Add(p[0], p[1]); | |
} | |
} | |
public void Add(int x, int y) | |
{ | |
if (!grid.ContainsKey(x)) | |
grid[x] = new Dictionary<int, int>(); | |
grid[x][y] = 1; | |
} | |
public bool Exists(int x, int y) => grid.ContainsKey(x) && grid[x].ContainsKey(y); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment