LeetCode 999: Available Captures for Rook Solution
Master LeetCode problem 999 (Available Captures for Rook), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
999. Available Captures for Rook
Problem Explanation
Explanation:
- We need to find the number of pawns that the white rook is attacking on the chessboard.
- We can find the white rook's position and then check in all four directions (up, down, left, right) for any pawns.
- If we encounter a bishop before reaching a pawn in any direction, we stop searching in that direction.
- We increment a counter for each pawn found in the rook's line of sight.
Time Complexity: O(1) as the chessboard size is fixed (8x8)
Space Complexity: O(1)
Solution Code
class Solution {
public int numRookCaptures(char[][] board) {
int[] rookPos = new int[2];
int numCaptures = 0;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board[i][j] == 'R') {
rookPos[0] = i;
rookPos[1] = j;
break;
}
}
}
int[][] directions = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
for (int[] dir : directions) {
int x = rookPos[0] + dir[0];
int y = rookPos[1] + dir[1];
while (x >= 0 && x < 8 && y >= 0 && y < 8) {
if (board[x][y] == 'p') {
numCaptures++;
break;
} else if (board[x][y] == 'B') {
break;
}
x += dir[0];
y += dir[1];
}
}
return numCaptures;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 999 (Available Captures for Rook)?
This page provides optimized solutions for LeetCode problem 999 (Available Captures for Rook) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 999 (Available Captures for Rook)?
The time complexity for LeetCode 999 (Available Captures for Rook) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 999 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 999 in Java, C++, or Python.