## 3. 题目解析

### 方法一：模拟+方向数组+常规解法

``````// 执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户
// 内存消耗 :6.4 MB, 在所有 C++ 提交中击败了100.00%的用户

class Solution {
public:
int numRookCaptures(vector<vector<char>>& board) {
int cnt = 0, len = board.size();
for (int i = 0; i < len; ++i) {
for (int j = 0; j < len; ++j) {
if (board[i][j] == 'R') {
int row = i, col = j, flag = 0;
while (row - 1 > 0 && board[row][col] != 'B') {
--row;
if (board[row][col] == 'p' and flag == 0) ++cnt, flag = 1;
}
row = i, col = j, flag = 0;
while (row + 1 < len && board[row][col] != 'B') {
++row;
if (board[row][col] == 'p' and flag == 0) ++cnt, flag = 1;
}
row = i, col = j, flag = 0;
while (col - 1 > 0 && board[row][col] != 'B') {
--col;
if (board[row][col] == 'p' and flag == 0) ++cnt, flag = 1;
}
row = i, col = j, flag = 0;
while (col + 1 < len && board[row][col] != 'B') {
++col;
if (board[row][col] == 'p' and flag == 0) ++cnt, flag = 1;
}
return cnt;
}
}
}
return 0;
}
};
``````

``````// 执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户
// 内存消耗 :6.2 MB, 在所有 C++ 提交中击败了100.00%的用户

class Solution {
public:
int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int numRookCaptures(vector<vector<char>>& board) {
int cnt = 0, len = board.size();
for (int i = 0; i < len; ++i) {
for (int j = 0; j < len; ++j) {
if (board[i][j] == 'R') {
for (int k = 0; k < 4; ++k) {
int x = i, y = j;
while (1) {
x += dir[k][0];
y += dir[k][1];
if (x < 0 or x >=len or y < 0 or y>= 8 or board[x][y] == 'B') break;
if (board[x][y] == 'p') {
++cnt;
break;
}
}
}
return cnt;
}
}
}
return 0;
}
};
``````