|
| 1 | +/** |
| 2 | + * 999. Available Captures for Rook |
| 3 | + * https://leetcode.com/problems/available-captures-for-rook/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * You are given an 8 x 8 matrix representing a chessboard. There is exactly one white rook |
| 7 | + * represented by 'R', some number of white bishops 'B', and some number of black pawns 'p'. |
| 8 | + * Empty squares are represented by '.'. |
| 9 | + * |
| 10 | + * A rook can move any number of squares horizontally or vertically (up, down, left, right) |
| 11 | + * until it reaches another piece or the edge of the board. A rook is attacking a pawn if it |
| 12 | + * can move to the pawn's square in one move. |
| 13 | + * |
| 14 | + * Note: A rook cannot move through other pieces, such as bishops or pawns. This means a rook |
| 15 | + * cannot attack a pawn if there is another piece blocking the path. |
| 16 | + * |
| 17 | + * Return the number of pawns the white rook is attacking. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {character[][]} board |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var numRookCaptures = function(board) { |
| 25 | + let rookRow; |
| 26 | + let rookCol; |
| 27 | + |
| 28 | + for (let i = 0; i < 8; i++) { |
| 29 | + for (let j = 0; j < 8; j++) { |
| 30 | + if (board[i][j] === 'R') { |
| 31 | + rookRow = i; |
| 32 | + rookCol = j; |
| 33 | + break; |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + const result = countPawns(-1, 0) + countPawns(1, 0) |
| 39 | + + countPawns(0, -1) + countPawns(0, 1); |
| 40 | + |
| 41 | + return result; |
| 42 | + |
| 43 | + function countPawns(rowStep, colStep) { |
| 44 | + let row = rookRow + rowStep; |
| 45 | + let col = rookCol + colStep; |
| 46 | + |
| 47 | + while (row >= 0 && row < 8 && col >= 0 && col < 8) { |
| 48 | + if (board[row][col] === 'p') return 1; |
| 49 | + if (board[row][col] === 'B') return 0; |
| 50 | + row += rowStep; |
| 51 | + col += colStep; |
| 52 | + } |
| 53 | + return 0; |
| 54 | + } |
| 55 | +}; |
0 commit comments