Available Captures for Rook - Complete Solution Guide
Available Captures for Rook is LeetCode problem 999, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 bi
Detailed Explanation
The problem asks us to find the number of black pawns ('p') a white rook ('R') can attack on an 8x8 chessboard. The rook can move horizontally or vertically any number of squares until it encounters another piece (bishop 'B' or pawn 'p') or the edge of the board. A rook attacks a pawn if it can move to the pawn's square in one move without being blocked by another piece. We need to count the number of pawns the rook is attacking.
Solution Approach
The solution involves first finding the position of the rook on the board. Then, from the rook's position, it iterates in four directions (up, down, left, and right) until it either hits the edge of the board or encounters a piece (either a bishop or a pawn). If it encounters a pawn, the capture count is incremented. If it encounters a bishop, the search stops in that direction. The process is repeated for all four directions.
Step-by-Step Algorithm
- Step 1: Iterate through the board to find the row and column index of the rook ('R').
- Step 2: Initialize a capture count variable to 0.
- Step 3: Iterate upwards from the rook's position, checking each cell until the edge of the board or a piece is encountered. If a pawn ('p') is found, increment the capture count and stop the iteration in this direction. If a bishop ('B') is found, stop the iteration in this direction.
- Step 4: Repeat step 3 for the downward direction.
- Step 5: Repeat step 3 for the leftward direction.
- Step 6: Repeat step 3 for the rightward direction.
- Step 7: Return the final capture count.
Key Insights
- Insight 1: The rook can only capture the first pawn encountered in each direction (up, down, left, right).
- Insight 2: The presence of a bishop blocks the rook's attack in that direction.
- Insight 3: We need to iterate through the board in all four directions from the rook's position until we hit the board edge or encounter another piece.
Complexity Analysis
Time Complexity: O(1)
Space Complexity: O(1)
Topics
This problem involves: Array, Matrix, Simulation.
Companies
Asked at: Block.