#999
Available Captures for Rook
EasyArrayMatrixSimulationSimulationGrid Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution is similar to the brute force but focuses on stopping immediately when we encounter a piece, making it more efficient. We can also use a single loop to check each direction without needing to iterate through the entire board.
⚙️
Algorithm
3 steps- 1Step 1: Locate the rook's position on the board.
- 2Step 2: For each of the four directions, check until a piece is encountered.
- 3Step 3: If a pawn is found, increment the counter; if a bishop is found, stop checking in that direction.
solution.py20 lines
1def numRookCaptures(board):
2 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
3 count = 0
4 for i in range(8):
5 for j in range(8):
6 if board[i][j] == 'R':
7 rook_x, rook_y = i, j
8 break
9 for dx, dy in directions:
10 x, y = rook_x, rook_y
11 while 0 <= x < 8 and 0 <= y < 8:
12 x += dx
13 y += dy
14 if 0 <= x < 8 and 0 <= y < 8:
15 if board[x][y] == 'p':
16 count += 1
17 break
18 elif board[x][y] == 'B':
19 break
20 return countℹ
Complexity note: The optimal solution runs in O(n) because we only traverse the board in the four directions from the rook's position, stopping early when we hit a piece.
- 1Rooks attack in straight lines until blocked.
- 2Only pawns can be captured; bishops block the path.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.