EasyNo. 0999

Available Captures for Rook — LeetCode 999 Python Solution

Topics
Array, Matrix, Simulation
Reading time
3 min

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

PythonSolution
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 ans

Complexity

Time
O(m × n)where m and n are the number of rows and columns of the board, respectively
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0054Spiral MatrixMedium
0059Spiral Matrix IIMedium
0289Game of LifeMedium
0498Diagonal TraverseMedium
0566Reshape the MatrixEasy
0867Transpose MatrixEasy

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 × 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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.