Available Captures for Rook — LeetCode 999 Python Solution
- Problem
- #999
- Pattern
- Matrix and Grid
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an 8 x 8 matrix representing a chessboard. There is exactly one white rook represented by 'R', some number of white bishops 'B', and some number of black pawns 'p'.
Python solution
class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
dirs = (-1, 0, 1, 0, -1)
n = len(board)
for i in range(n):
for j in range(n):
if board[i][j] == "R":
ans = 0
for a, b in pairwise(dirs):
x, y = i + a, j + b
while 0 <= x < n and 0 <= y < n and board[x][y] != "B":
if board[x][y] == "p":
ans += 1
break
x, y = x + a, y + b
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n), where m and n are the number of rows and columns of the board, respectively |
| Space | O(1) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 999. Available Captures for Rook is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 999. Available Captures for Rook?
- LeetCode 999. Available Captures for Rook is rated Easy on LeetCode.
- What is the time complexity of LeetCode 999. Available Captures for Rook?
- The Python solution on this page runs in O(m \times n), where m and n are the number of rows and columns of the board, respectively.
- What is the space complexity of LeetCode 999. Available Captures for Rook?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 999. Available Captures for Rook cover?
- LeetCode 999. Available Captures for Rook is tagged Array, Matrix and Simulation on LeetCode.