Skip to content

Commit f896522

Browse files
authored
Create available-captures-for-rook.cpp
1 parent 2083a7b commit f896522

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

C++/available-captures-for-rook.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Time: O(1)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int numRookCaptures(vector<vector<char>>& board) {
7+
static vector<pair<int, int>> directions{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
8+
9+
int r = -1, c = -1;
10+
for (int i = 0; i < 8 && r == -1; ++i) {
11+
for (int j = 0; j < 8; ++j) {
12+
if (board[i][j] == 'R') {
13+
tie(r, c) = make_pair(i, j);
14+
break;
15+
}
16+
}
17+
}
18+
19+
int result = 0;
20+
for(const auto& d : directions) {
21+
int nr, nc;
22+
tie(nr, nc) = make_pair(r + d.first, c + d.second);
23+
while (0 <= nr && nr < 8 && 0 <= nc && nc < 8) {
24+
if (board[nr][nc] == 'p') {
25+
++result;
26+
}
27+
if (board[nr][nc] != '.') {
28+
break;
29+
}
30+
tie(nr, nc) = make_pair(nr + d.first, nc + d.second);
31+
}
32+
}
33+
return result;
34+
}
35+
};

0 commit comments

Comments
 (0)