1222. 可以攻击国王的皇后

47 阅读1分钟

leetcode.cn/problems/qu…

从国王出发,探索八个方向上距离最近的皇后,加入到结果集中。

image.png

class Solution {
    public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {
        List<List<Integer>> ans = new ArrayList<>();
        int kx = king[0], ky = king[1];
        Map<Integer, TreeSet<Integer>> qx2allQy = new HashMap<>();
        for (int[] q : queens) {
            TreeSet<Integer> tmp = qx2allQy.getOrDefault(q[0], new TreeSet<>());
            tmp.add(q[1]);
            qx2allQy.put(q[0], tmp);
        }

        boolean found1 = false, found2 = false, found3 = false;
        for (int i = 1; kx - i >= 0; ++i) {
            int x = kx - i;
            int y1 = ky + i, y2 = ky, y3 = ky - i;
            TreeSet<Integer> queensY = qx2allQy.get(x);
            if (queensY == null) {
                continue;
            }
            if (found1 && found2 && found3) {
                break;
            }
            if (queensY.contains(y1) && !found1) {
                ans.add(createList(x, y1));
                found1 = true;
            }
            if (queensY.contains(y2) && !found2) {
                ans.add(createList(x, y2));
                found2 = true;
            }
            if (queensY.contains(y3) && !found3) {
                ans.add(createList(x, y3));
                found3 = true;
            }
        }

        found1 = false;
        found2 = false;
        found3 = false;
        for (int i = 1; kx + i < 8; ++i) {
            int x = kx + i;
            int y1 = ky + i, y2 = ky, y3 = ky - i;
            TreeSet<Integer> queensY = qx2allQy.get(x);
            if (queensY == null) {
                continue;
            }
            
            if (found1 && found2 && found3) {
                break;
            }
            if (queensY.contains(y1) && !found1) {
                ans.add(createList(x, y1));
                found1 = true;
            }
            if (queensY.contains(y2) && !found2) {
                ans.add(createList(x, y2));
                found2 = true;
            }
            if (queensY.contains(y3) && !found3) {
                ans.add(createList(x, y3));
                found3 = true;
            }
        }


        TreeSet<Integer> queensY = qx2allQy.get(kx);
        if (queensY != null) {
            Integer floor = queensY.floor(ky);
            Integer ceil = queensY.ceiling(ky);
            if (floor != null) {
                ans.add(createList(kx, floor));
            }
            if (ceil != null) {
                ans.add(createList(kx, ceil));
            }
        }
        return ans;

    }
    private List<Integer> createList(int x, int y) {
        List<Integer> ret = new ArrayList<>();
        ret.add(x);
        ret.add(y);
        return ret;
    }
}

皇后的数量是n,

  • 空间复杂度:O(n),哈希表存储所有皇后
  • 时间复杂度:O(n),最坏会遍历所有的皇后