You are given an 8x8 chessboard board
with the following pieces:
You need to calculate the number of pawns the Rook can capture. The Rook moves horizontally or vertically until it hits another piece or the edge of the board. It can capture any pawn in these directions (not blocked by other pieces).
Let’s implement this step-by-step.
def numRookCaptures(board):
# Helper function to find the position of the Rook 'R'
def find_rook(board):
for i in range(8):
for j in range(8):
if board[i][j] == 'R':
return (i, j)
return (-1, -1) # Should not happen since we assume exactly one Rook is present.
# Function to count captures in a specific direction
def count_in_direction(board, start_i, start_j, delta_i, delta_j):
i, j = start_i + delta_i, start_j + delta_j
while 0 <= i < 8 and 0 <= j < 8:
if board[i][j] == 'B': # blocked by Bishop
return 0
if board[i][j] == 'p': # found a Pawn
return 1
i += delta_i
j += delta_j
return 0
rook_i, rook_j = find_rook(board)
captures = 0
# Check all four directions
captures += count_in_direction(board, rook_i, rook_j, -1, 0) # Up
captures += count_in_direction(board, rook_i, rook_j, 1, 0) # Down
captures += count_in_direction(board, rook_i, rook_j, 0, -1) # Left
captures += count_in_direction(board, rook_i, rook_j, 0, 1) # Right
return captures
# Example usage:
board = [
[".",".",".",".",".",".",".","."],
[".",".",".","p",".",".",".","."],
[".",".",".","R",".",".",".","p"],
[".",".",".",".",".",".",".","."],
[".",".",".",".",".",".",".","."],
[".",".",".","p",".",".",".","."],
[".",".",".",".",".",".",".","."],
[".",".",".",".",".",".",".","."]
]
print(numRookCaptures(board)) # Output should be 3.
The time complexity is O(1). This is because:
8x8 = 64
operations.This solution ensures we efficiently check each necessary direction and thus determine the number of pawns the Rook can capture within the constraints given.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?