LintCode 322: Chess Game

该博客介绍了如何解决一个棋盘游戏中,判断骑士是否会被皇后的攻击的问题。通过创建集合存储皇后的位置信息,然后检查每个骑士的位置是否在同行、同列、同对角线,从而快速得出结论。算法复杂度较低,适用于大量皇后和骑士的情况。

322. Chess Game

In a game of chess, you are given two binary arrays:

a binary array queen with size N, which represents the coordinates of N queens;

a binary array knight with size M, which represents the coordinates of M knights.

A queen can attack any knight chess in the same row, column and diagonal.

You are asked to return an answer array with size M, the ith element of which shows whether the ith knight can be attacked.

 

Example

Example:

Input: [[1,1],[2,2]]

[[3,3],[1,3],[4,5]]

Output: [true,true,false]

Explanation: The first knight can be attacked by queen 1 and 2.

The second knight can be attacked by queen 1 and 2.

The last knight can not be attacked.

 

Notice

1≤N,M≤10^​5

​​ 

The range of chess coordinates is a positive integer from 1 to 10^9

​​ 解法1:
注意主对角线可以用row-col来确定,反对角线可以用row+col来确定。

class Solution {
public:
    /**
     * @param queen: queen‘coordinate
     * @param knight: knight‘coordinate
     * @return: if knight is attacked please return true,else return false
     */
    vector<bool> isAttacked(vector<vector<int>> &queen, vector<vector<int>> &knight) {
        int len_q = queen.size();
        int len_k = knight.size();
        vector<bool> result(len_k, true);
        unordered_set<int> row_set;
        unordered_set<int> col_set;
        unordered_set<int> diag_set;
        unordered_set<int> rev_diag_set;
        
        for (int i = 0; i < len_q; ++i) {
            row_set.insert(queen[i][0]);
            col_set.insert(queen[i][1]);
            diag_set.insert(queen[i][0] - queen[i][1]);
            rev_diag_set.insert(queen[i][0] + queen[i][1]);
        }
        
        for (int i = 0; i < len_k; ++i) {
            if (row_set.find(knight[i][0]) == row_set.end() &&
                col_set.find(knight[i][1]) == col_set.end() &&
                diag_set.find(knight[i][0] - knight[i][1]) == diag_set.end() &&
                rev_diag_set.find(knight[i][0] + knight[i][1]) == rev_diag_set.end())
            
            result[i] = false;    
        }
        
        return result;
    }
};


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值