Skip to content

999. Available Captures for Rook

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  int numRookCaptures(vector<vector<char>>& board) {
    int ans = 0;
    int i0 = 0;
    int j0 = 0;

    for (int i = 0; i < 8; ++i)
      for (int j = 0; j < 8; ++j)
        if (board[i][j] == 'R') {
          i0 = i;
          j0 = j;
        }

    for (const vector<int>& d :
         vector<vector<int>>({{1, 0}, {0, 1}, {-1, 0}, {0, -1}}))
      for (int i = i0 + d[0], j = j0 + d[1]; 0 <= i && i < 8 && 0 <= j && j < 8;
           i += d[0], j += d[1]) {
        if (board[i][j] == 'p')
          ++ans;
        if (board[i][j] != '.')
          break;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
  public int numRookCaptures(char[][] board) {
    int ans = 0;
    int i0 = 0;
    int j0 = 0;

    for (int i = 0; i < 8; ++i)
      for (int j = 0; j < 8; ++j)
        if (board[i][j] == 'R') {
          i0 = i;
          j0 = j;
        }

    for (int[] d : new int[][] {{1, 0}, {0, 1}, {-1, 0}, {0, -1}})
      for (int i = i0 + d[0], j = j0 + d[1]; 0 <= i && i < 8 && 0 <= j && j < 8;
           i += d[0], j += d[1]) {
        if (board[i][j] == 'p')
          ++ans;
        if (board[i][j] != '.')
          break;
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
  def numRookCaptures(self, board: list[list[str]]) -> int:
    ans = 0

    for i in range(8):
      for j in range(8):
        if board[i][j] == 'R':
          i0 = i
          j0 = j

    for d in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
      i = i0 + d[0]
      j = j0 + d[1]
      while 0 <= i < 8 and 0 <= j < 8:
        if board[i][j] == 'p':
          ans += 1
        if board[i][j] != '.':
          break
        i += d[0]
        j += d[1]

    return ans