Leetcode 999. Available Captures for Rook
You are given an 8x8 chessboard represented as a 2D character array board
.
The white rook can move along the row or column, and it can attack (capture) the black pawns.
However, it cannot pass through black bishops. The rook’s maximum block distance is thus limited by any bishops along the same row or column.
Return the number of pawns the rook can capture in one move.
public class Solution {
public int numRookCaptures(char[][] board) {
int rookRow = -1, rookCol = -1;
// Step 1: Find the position of the Rook
outerLoop:
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board[i][j] == 'R') {
rookRow = i;
rookCol = j;
break outerLoop;
}
}
}
int captures = 0;
// Step 2: Check in all four directions from the Rook's position
// Check upward
for (int i = rookRow - 1; i >= 0; i--) {
if (board[i][rookCol] == 'B') break;
if (board[i][rookCol] == 'p') {
captures++;
break;
}
}
// Check downward
for (int i = rookRow + 1; i < 8; i++) {
if (board[i][rookCol] == 'B') break;
if (board[i][rookCol] == 'p') {
captures++;
break;
}
}
// Check leftward
for (int j = rookCol - 1; j >= 0; j--) {
if (board[rookRow][j] == 'B') break;
if (board[rookRow][j] == 'p') {
captures++;
break;
}
}
// Check rightward
for (int j = rookCol + 1; j < 8; j++) {
if (board[rookRow][j] == 'B') break;
if (board[rookRow][j] == 'p') {
captures++;
break;
}
}
return captures;
}
}
Overall, the time complexity is O(1), making the solution very efficient due to the constant board size.
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?