-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
59 lines (56 loc) · 1.33 KB
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* @param {number[][]} queens
* @param {number[]} king
* @return {number[][]}
*/
var queensAttacktheKing = function (queens, king) {
const queensMap = {};
const deltas = [
[
0, 1, ],
[
0, -1, ],
[
1, 0, ],
[
-1, 0, ],
[
1, 1, ],
[
-1, -1, ],
[
1, -1, ],
[
-1, 1, ],
];
for (let i = 0; i < queens.length; i++) {
const [
x, y, ] = queens[i];
queensMap[`${x},${y}`] = true;
}
const result = [];
const usedQueenMap = {};
const [
x, y, ] = king;
// 在各个方向寻找最近的Queen
for (let j = 0; j < deltas.length; j++) {
let curX = x;
let curY = y;
const [
deltax, deltay, ] = deltas[j];
while (curX + deltax > -1 && curX + deltax < 8 && curY + deltay > -1 && curY + deltay < 8) {
curX += deltax;
curY += deltay;
if (usedQueenMap[`${curX},${curY}`]) {
break;
}
if (queensMap[`${curX},${curY}`]) {
usedQueenMap[`${curX},${curY}`] = true;
result.push([
curX, curY, ]);
break;
}
}
}
return result;
};