Available Captures for Rook
Problem
On an 8 x 8
chessboard, there is exactly one white rook 'R'
and some number of white bishops 'B'
, black pawns 'p'
, and empty squares '.'
.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook’s turn. The number of available captures for the white rook is the number of pawns that the rook is attacking.
Return the number of available captures for the white rook.
Constraints
board.length == 8
board[i].length == 8
board[i][j]
is either'R'
,'.'
,'B'
, or'p'
- There is exactly one cell with
board[i][j] == 'R'
Solution
The problem Available Captures for Rook
can be solved by finding the rook and then counting pawns on four cardinal directions from the rook that are not blocked by bishops.
Implementation
static const int fast_io = []()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution
{
public:
int numRookCaptures(vector<vector<char>> &board)
{
int col, row;
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
if (board[i][j] == 'R')
{
row = i;
col = j;
break;
}
int count = 0;
for (int i = col; i > 0; i--)
{
if (board[row][i - 1] != '.')
{
if (board[row][i - 1] == 'p')
count += 1;
break;
}
}
for (int i = col + 1; i < 8; i++)
{
if (board[row][i] != '.')
{
if (board[row][i] == 'p')
count += 1;
break;
}
}
for (int i = row; i > 0; i--)
{
if (board[i - 1][col] != '.')
{
if (board[i - 1][col] == 'p')
count += 1;
break;
}
}
for (int i = row + 1; i < 8; i++)
{
if (board[i][col] != '.')
{
if (board[i][col] == 'p')
count += 1;
break;
}
}
return count;
}
};