Skip to content

Commit 534ab44

Browse files
authored
Create 10036-minimum-moves-to-capture-the-queen.js
1 parent a7ceeb1 commit 534ab44

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/**
2+
* @param {number} a
3+
* @param {number} b
4+
* @param {number} c
5+
* @param {number} d
6+
* @param {number} e
7+
* @param {number} f
8+
* @return {number}
9+
*/
10+
var minMovesToCaptureTheQueen = function(a, b, c, d, e, f) {
11+
if(rook() || bishop()) return 1
12+
13+
return 2
14+
15+
function rook() {
16+
if(a === e) {
17+
const min = Math.min(b,f), max = Math.max(b,f)
18+
if(c !== a) return true
19+
else if(d < min || d > max) return true
20+
else return false
21+
}
22+
if(b === f) {
23+
const min = Math.min(a,e), max = Math.max(a,e)
24+
if(d !== b) return true
25+
else if(c < min || c > max) return true
26+
else return false
27+
}
28+
29+
return false
30+
}
31+
function bishop() {
32+
// c,d,e,f
33+
34+
const dirs = [[-1, -1], [-1, 1], [1, -1], [1, 1]]
35+
const visited = new Set()
36+
const target = `${e},${f}`
37+
const key = (x, y) => `${x},${y}`
38+
39+
const ss = new Set()
40+
// top-left
41+
let x = c, y = d
42+
let dd = dirs[0]
43+
while(x + dd[0]>= 1 && x + dd[0]<= 8 && y+ dd[1] >= 1 && y+dd[1] <= 8 && (!(x + dd[0] === a && y +dd[1] === b))) {
44+
ss.add(key(x +dd[0], y +dd[1]))
45+
x += dd[0]
46+
y += dd[1]
47+
}
48+
49+
// top-right
50+
x = c, y = d
51+
dd = dirs[1]
52+
while(x + dd[0]>= 1 && x + dd[0]<= 8 && y+ dd[1] >= 1 && y+dd[1] <= 8 && (!(x + dd[0] === a && y +dd[1] === b))) {
53+
ss.add(key(x +dd[0], y +dd[1]))
54+
x += dd[0]
55+
y += dd[1]
56+
}
57+
58+
// bottom-left
59+
x = c, y = d
60+
dd = dirs[2]
61+
while(x + dd[0]>= 1 && x + dd[0]<= 8 && y+ dd[1] >= 1 && y+dd[1] <= 8 && (!(x + dd[0] === a && y +dd[1] === b))) {
62+
ss.add(key(x +dd[0], y +dd[1]))
63+
x += dd[0]
64+
y += dd[1]
65+
}
66+
67+
// bottom-right
68+
x = c, y = d
69+
dd = dirs[3]
70+
while(x + dd[0]>= 1 && x + dd[0]<= 8 && y+ dd[1] >= 1 && y+dd[1] <= 8 && (!(x + dd[0] === a && y +dd[1] === b))) {
71+
ss.add(key(x +dd[0], y +dd[1]))
72+
x += dd[0]
73+
y += dd[1]
74+
}
75+
if(ss.has(target)) return true
76+
77+
78+
return false
79+
}
80+
};

0 commit comments

Comments
 (0)