#999. Available Captures for Rook
On an 8 x 8 chessboard, there is one white rook. There also may be empty squares, white bishops, and black pawns. These are given as characters ‘R’, ‘.’, ‘B’, and ‘p’ respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces.
The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies. Also, rooks cannot move into the same square as other friendly bishops.
Return the number of pawns the rook can capture in one move.
这道题我读了好多好多遍,才读懂…其实很简单,问的是在R只走一步的情况下,有几种可能可以吃掉p,且如果R和p之间有B,也不能吃的。…所以就按照上下左右四种情况分类讨论。
/**
* @param {character[][]} board
* @return {number}
*/
var numRookCaptures = function(board) {
var row=0;
var col=0;
var result=0;
for(let i=0;i<board.length;i++) {
for(let j=0;j<board.length;j++) {
if(board[i][j]==='R') {
row=i;
col=j;
break;
}
}
}
for(let i=row-1;i>=0;i--) {
if(board[i][col]==='p') {
result++;
break;
}
if(board[i][col]==='B') {
break;
}
}
for(let i=row+1;i<board.length;i++) {
if(board[i][col]==='p') {
result++;
break;
}
if(board[i][col]==='B') {
break;
}
}
for(let i=col-1;i>=0;i--) {
if(board[row][i]==='p') {
result++;
break;
}
if(board[row][i]==='B') {
break;
}
}
for(let i=col+1;i<board[row].length;i++) {
if(board[row][i]==='p') {
result++;
break;
}
if(board[row][i]==='B') {
break;
}
}
return result;
};