Available Captures for Rook LeetCode solution in JavaScript

1
var numRookCaptures = function (board) {
2
const r = board.length;
3
const c = board[0].length;
4

5
let res = 0;
6
const dir = [
7
[0, 1],
8
[0, -1],
9
[1, 0],
10
[-1, 0],
11
]; // all the 4 possible directions
12
let rook = [];
13

14
// finding the rook's position
15
for (let i = 0; i < r; i++) {
16
for (let j = 0; j < c; j++) {
17
if (board[i][j] === "R") {
18
rook = [i, j];
19
break;
20
}
21
}
22
}
23

24
// traversing all the 4 directions
25
for (let [x, y] of dir) {
26
res += helper(x, y, rook[0], rook[1]);
27
}
28

29
return res;
30

31
function helper(x, y, i, j) {
32
let newX = x + i;
33
let newY = y + j;
34
let attack = 0;
35
while (newX < r && newY < c && newX >= 0 && newY >= 0) {
36
if (board[newX][newY] === "p") {
37
attack++;
38
break; // break because Rook can't attack more than one pawn in same direction
39
} else if (board[newX][newY] === "B") {
40
break;
41
}
42
// keep moving towards the same direction
43
newX += x;
44
newY += y;
45
}
46
return attack;
47
}
48
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0