# LeetCode-3.26-999-E-车的可用捕获量（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.

# 思路

（1）找“白车”。双重循环的遍历，没什么好解释。唯一需要注意的是如何跳出双重循环并记录下白车的坐标。这里使用的是 break label。另外一种使用布尔值控制，如下代码不可行，当flag == true后，j仍旧会进行+1的操作，然后进行下次循环判断时才不进入，同理i也会进行+1的操作。这样“白象”的坐标就变动了。

        boolean flag = false;
for(i = 0; i < len && !flag; i++){
for( j = 0; j < len && !flag; j++){
if(board[i][j] == 'R'){
flag = true;
}
}
}


（2）在“白车”的四个方向寻找“黑卒”和“白象”。以“白车”为中心点向四个方向进行搜索，需要白象就跳出当前方向，被阻挡，遇到黑卒就+1，然后跳出。

# 解法

class Solution {
public int numRookCaptures(char[][] board) {
int len = board.length;
int i = 0, j = 0;
// 1. find the white Rook
label:
for(; i < len; i++){
for(j = 0; j < len; j++){ //error
if(board[i][j] == 'R'){
// flag = true;
break label;
}
}
}
int count = 0;
//2. find 4 directions
for(int r1 = i; r1 >= 0; r1-- ){
if(board[r1][j] =='B'){
break;
}
if(board[r1][j] == 'p'){
count++;
break;
}
}

for( int r2 = i; r2 < len; r2++){
if(board[r2][j] =='B'){
break;
}
if(board[r2][j] == 'p'){
count++;
break;
}
}

for(int c1 = j; c1 >= 0; c1--){
if(board[i][c1] =='B'){
break;
}
if(board[i][c1] == 'p'){
count++;
break;
}
}

for(int c2 = j; c2 < len; c2++){
if(board[i][c2] =='B'){
break;
}
if(board[i][c2] == 'p'){
count++;
break;
}
}

return count;
}
}


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客