Available Captures for Rook

easy array matrix simulation

Problem

On an 8×8 chessboard, there is exactly one white rook 'R', some white bishops 'B', some black pawns 'p', and empty squares '.'. The rook moves horizontally or vertically until it chooses to stop, reaches the edge, captures a black pawn, or is blocked by a white bishop. Return the number of pawns the rook can capture in one move.

Inputboard with R at (4,3), pawns left/right/up, bishop blocking down
Output3
The rook captures the first pawn it meets going left, right, and up; the bishop blocks the downward path.

def num_rook_captures(board):
    for r in range(8):
        for c in range(8):
            if board[r][c] == 'R':
                rr, rc = r, c
    captures = 0
    for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
        nr, nc = rr + dr, rc + dc
        while 0 <= nr < 8 and 0 <= nc < 8:
            if board[nr][nc] == 'B':
                break
            if board[nr][nc] == 'p':
                captures += 1
                break
            nr += dr
            nc += dc
    return captures
function numRookCaptures(board) {
  let rr, rc;
  for (let r = 0; r < 8; r++)
    for (let c = 0; c < 8; c++)
      if (board[r][c] === 'R') { rr = r; rc = c; }
  let captures = 0;
  const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]];
  for (const [dr, dc] of dirs) {
    let nr = rr + dr, nc = rc + dc;
    while (nr >= 0 && nr < 8 && nc >= 0 && nc < 8) {
      if (board[nr][nc] === 'B') break;
      if (board[nr][nc] === 'p') { captures++; break; }
      nr += dr; nc += dc;
    }
  }
  return captures;
}
class Solution {
    public int numRookCaptures(char[][] board) {
        int rr = 0, rc = 0;
        for (int r = 0; r < 8; r++)
            for (int c = 0; c < 8; c++)
                if (board[r][c] == 'R') { rr = r; rc = c; }
        int captures = 0;
        int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        for (int[] d : dirs) {
            int nr = rr + d[0], nc = rc + d[1];
            while (nr >= 0 && nr < 8 && nc >= 0 && nc < 8) {
                if (board[nr][nc] == 'B') break;
                if (board[nr][nc] == 'p') { captures++; break; }
                nr += d[0]; nc += d[1];
            }
        }
        return captures;
    }
}
int numRookCaptures(vector<vector<char>>& board) {
    int rr = 0, rc = 0;
    for (int r = 0; r < 8; r++)
        for (int c = 0; c < 8; c++)
            if (board[r][c] == 'R') { rr = r; rc = c; }
    int captures = 0;
    int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    for (auto& d : dirs) {
        int nr = rr + d[0], nc = rc + d[1];
        while (nr >= 0 && nr < 8 && nc >= 0 && nc < 8) {
            if (board[nr][nc] == 'B') break;
            if (board[nr][nc] == 'p') { captures++; break; }
            nr += d[0]; nc += d[1];
        }
    }
    return captures;
}
Time: O(1) Space: O(1)