计算几何-Minimum Area Rectangle II

2020-02-10 21:02:13

问题描述:

问题求解:

本题由于可以暴力求解,所以不是特别难,主要是用来熟悉计算几何的一些知识点的。

    public double minAreaFreeRect(int[][] points) {
        double res = 2e9;
        Map<Integer, Set<Integer>> record = new HashMap<>();
        for (int[] p : points) {
            int x = p[0];
            int y = p[1];
            if (!record.containsKey(x)) record.put(x, new HashSet<>());
            record.get(x).add(y);
        }
        int n = points.length;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                for (int k = j + 1; k < n; k++) {
                    if (check(points[i], points[j], points[k]) && record.containsKey(points[j][0] + points[k][0] - points[i][0]) && record.get(points[j][0] + points[k][0] - points[i][0]).contains(points[j][1] + points[k][1] - points[i][1])) {
                        res = Math.min(res, area(points[i], points[j], points[k]));
                    }
                }
            }
        }
        return res == 2e9 ? 0 : res;
    }
    
    private boolean check(int[] p1, int[] p2, int[] p3) {
        return (p2[0] - p1[0]) * (p3[0] - p1[0]) + (p2[1] - p1[1]) * (p3[1] - p1[1]) == 0;
    }
    
    private double area(int[] p1, int[] p2, int[] p3) {
        return Math.abs(p1[0] * p2[1] + p1[1] * p3[0] + p2[0] * p3[1] -
        p2[1] * p3[0] - p1[1] * p2[0] - p1[0] * p3[1]);
    }

  

posted @ 2020-02-10 21:04  hyserendipity  阅读(193)  评论(0编辑  收藏  举报