【Leetcode】1222. Queens That Can Attack the King

題目地址:

https://leetcode.com/problems/queens-that-can-attack-the-king/

給定一個8×88\times8棋盤的若干座標,橫縱座標範圍爲070\sim 7,這些座標上有國際象棋裏的皇后,再給定一個座標代表國王的位置(國王不會和皇后重合),問能攻擊到國王的皇后座標。注意能攻擊到國王的皇后,攻擊路徑上不能有其他棋子。

可以先將所有皇后的座標加入一個哈希表,然後從國王的位置向八個方向走,每遍歷一個方向的時候,遇到的第一個皇后就加入最終結果並退出循環,繼續搜索下一個方向。代碼如下:

import java.util.*;

public class Solution {
    
    class Pair {
        int x, y;
        
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
        
        @Override
        public boolean equals(Object o) {
            Pair pair = (Pair) o;
            return x == pair.x && y == pair.y;
        }
        
        @Override
        public int hashCode() {
            return Objects.hash(x, y);
        }
    }
    
    public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {
        List<List<Integer>> res = new ArrayList<>();
        
        if (queens == null || queens.length == 0) {
            return res;
        }
        
        // 加入所有皇后座標
        Set<Pair> set = new HashSet<>();
        for (int[] coord : queens) {
            set.add(new Pair(coord[0], coord[1]));
        }
        
        // 開個數組表示八個方向
        int[][] d = {{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}};
        for (int i = 0; i < d.length; i++) {
            int x = king[0], y = king[1], curX = x, curY = y;
            while (0 <= curX && curX < 8 && 0 <= curY && curY < 8) {
                curX += d[i][0];
                curY += d[i][1];
                if (set.contains(new Pair(curX, curY))) {
                    res.add(new ArrayList<>(Arrays.asList(curX, curY)));
                    break;
                }
            }
        }
        
        return res;
    }
}

時空複雜度O(n)O(n)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章