Problem
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.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
board.length == 8
board[i].length == 8
board[i][j]
is either'R'
,'.'
,'B'
, or'p'
- There is exactly one cell with
board[i][j] == 'R'
Solution
Method 1 – Directional Scan
Intuition
The rook can attack pawns in its row and column until it hits a blocking piece (bishop or board edge). By scanning in all four directions from the rook’s position, we can count all pawns it can attack.
Approach
- Find the position
(r, c)
of the rook'R'
on the board. - For each of the four directions (up, down, left, right):
- Move step by step from the rook’s position.
- If a bishop
'B'
is encountered, stop scanning in that direction. - If a pawn
'p'
is encountered, increment the answer and stop scanning in that direction. - If an empty square
'.'
is encountered, continue scanning.
- Return the total count of pawns the rook can attack.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
(since the board is always 8x8, all operations are constant time) - 🧺 Space complexity:
O(1)
(no extra space used except a few variables)