Skip to main content
Back to problems
#999
Easy Algorithms

Available captures for rook

Array Matrix Simulation
71.5% acceptance
Feb 25, 2026
803
646
You are given an 8 x 8 matrix representing a chessboard. There is exactly one white rook represented by 'R', some number of white bishops 'B', and some number of black pawns 'p'. Empty squares are represented by '.'. A rook can move any number of squares horizontally or vertically (up, down, left, right) until it reaches another piece or the edge of the board. A rook is attacking a pawn if it can move to the pawn's square in one move. Note: A rook cannot move through other pieces, such as bishops or pawns. This means a rook cannot attack a pawn if there is another piece blocking the path. Return the number of pawns the white rook is attacking.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn num_rook_captures(board: Vec<Vec<char>>) -> i32 {
    let (mut r, mut c) = (0, 0);
    for i in 0..8 { for j in 0..8 { if board[i][j] == 'R' { r = i; c = j; } } }
    let mut count = 0;
    for (dr, dc) in [(!0usize,0usize),(1,0),(0,!0usize),(0,1)] {
      let (mut nr, mut nc) = (r, c);
      loop {
        nr = nr.wrapping_add(dr); nc = nc.wrapping_add(dc);
        if nr >= 8 || nc >= 8 { break; }
        if board[nr][nc] == 'B' { break; }
        if board[nr][nc] == 'p' { count += 1; break; }
      }
    }
    count
  }
}