1
+ #include < vector>
2
+ #include < algorithm>
3
+ #include < iostream>
4
+ using namespace std ;
5
+
6
+ class Solution {
7
+ const int dx[4 ] = {-1 , 0 , 0 , 1 };
8
+ const int dy[4 ] = {0 , 1 , -1 , 0 };
9
+ const int N = 8 ;
10
+ public:
11
+ int numRookCaptures (vector<vector<char >>& board) {
12
+ int pCount = 0 ;
13
+ for (int i = 0 ; i < N; i++)
14
+ {
15
+ for (int j = 0 ; j < N; j++)
16
+ {
17
+ if (board[i][j] == ' R' )
18
+ {
19
+ // 一旦发现一个 'R', 就检测其上下左右4个方向
20
+ for (int k = 0 ; k < 4 ; k++)
21
+ {
22
+ int nx = i, ny = j;
23
+ while (nx >= 0 && nx < N && ny >= 0 && ny < N) /* 如果没越界 */
24
+ {
25
+ if (board[nx][ny] == ' B' ) /* 遇到自己一方的象B时, 停在原处 */
26
+ break ;
27
+ else if (board[nx][ny] == ' p' ) /* 遇到对方的卒p时, 进入该格子, 然后停止 */
28
+ {
29
+ pCount++;
30
+ break ;
31
+ }
32
+ nx += dx[k];
33
+ ny += dy[k];
34
+ }
35
+ }
36
+ // 题意: 棋盘上最多只有一个 'R' 存在
37
+ return pCount;
38
+ }
39
+ }
40
+ }
41
+ // 如果棋盘上没有车(R)或棋盘上没有能吃掉的卒
42
+ return 0 ;
43
+ }
44
+ };
45
+
46
+ // Test
47
+ int main ()
48
+ {
49
+ Solution sol;
50
+ vector<vector<char >> board =
51
+ {
52
+ {' .' ,' .' ,' .' ,' .' ,' .' ,' .' ,' .' ,' .' },
53
+ {' .' ,' .' ,' .' ,' p' ,' .' ,' .' ,' .' ,' .' },
54
+ {' .' ,' .' ,' .' ,' R' ,' .' ,' .' ,' .' ,' p' },
55
+ {' .' ,' .' ,' .' ,' .' ,' .' ,' .' ,' .' ,' .' },
56
+ {' .' ,' .' ,' .' ,' .' ,' .' ,' .' ,' .' ,' .' },
57
+ {' .' ,' .' ,' .' ,' p' ,' .' ,' .' ,' .' ,' .' },
58
+ {' .' ,' .' ,' .' ,' .' ,' .' ,' .' ,' .' ,' .' },
59
+ {' .' ,' .' ,' .' ,' .' ,' .' ,' .' ,' .' ,' .' }
60
+ };
61
+ auto res = sol.numRookCaptures (board);
62
+ cout << res << endl;
63
+
64
+ return 0 ;
65
+ }
0 commit comments