Skip to content

1222. Queens That Can Attack the King

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

js
/**
 * @param {number[][]} queens
 * @param {number[]} king
 * @return {number[][]}
 */
var queensAttacktheKing = function(queens, king) {
    const qs = {
        n: null,
        ne: null,
        e: null,
        se: null,
        s: null,
        sw: null,
        w: null,
        nw: null
    }

    for (let queen of queens) {
        // north, south
        if (queen[1] === king[1]) {
            if (queen[0] < king[0]) {
                if (!qs.n || qs.n[0] < queen[0]) {
                    qs.n = queen
                }
            } else {
                if (!qs.s || qs.s[0] > queen[0]) {
                    qs.s = queen
                }
            }
        }

        // west, east
        if (queen[0] === king[0]) {
            if (queen[1] < king[1]) {
                if (!qs.w || qs.w[1] < queen[1]) {
                    qs.w = queen
                }
            } else {
                if (!qs.e || qs.e[1] > queen[1]) {
                    qs.e = queen
                }
            }
        }

        // northeast, southwest
        if ((queen[0] - king[0]) === (queen[1] - king[1])) {
            if (queen[0] < king[0]) {
                if (!qs.ne || qs.ne[0] < queen[0]) {
                    qs.ne = queen
                }
            } else {
                if (!qs.sw || qs.sw[0] > queen[0]) {
                    qs.sw = queen
                }
            }
        }

        // northwest, southeast
        if ((queen[0] - king[0]) === (king[1] - queen[1])) {
            if (queen[0] < king[0]) {
                if (!qs.nw || qs.nw[0] < queen[0]) {
                    qs.nw = queen
                }
            } else {
                if (!qs.se || qs.se[0] > queen[0]) {
                    qs.se = queen
                }
            }
        }
    }

    return Object.keys(qs).reduce((ret, key) => {
        if (qs[key]) {
            ret.push(qs[key])
        }
        return ret
    }, [])
};