Problem 999

Abstract / Summary

A chess rook can capture certain pieces on an empty board depending on its position and other pieces present.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0999.py

class Solution:
    def numRookCaptures(self, board: List[List[str]]) -> int:
        result = 0
        for y in range(8):
            for x in range(8):
                if board[y][x] == "R":
                    for dx in range(x - 1, -1, -1):
                        if board[y][dx] == "p":
                            result += 1
                        if board[y][dx] != ".":
                            break
                    for dx in range(x + 1, 8):
                        if board[y][dx] == "p":
                            result += 1
                        if board[y][dx] != ".":
                            break
                    for dy in range(y - 1, -1, -1):
                        if board[dy][x] == "p":
                            result += 1
                        if board[dy][x] != ".":
                            break
                    for dy in range(y + 1, 8):
                        if board[dy][x] == "p":
                            result += 1
                        if board[dy][x] != ".":
                            break
        return result
27 lines | 1121 bytes | submitted October 23, 2023 | GitHub   tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 72% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Matrix
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes how many enemy pawns a white rook can capture on a standard 8 × 8 chessboard. The board is represented as a list of eight lists, each containing a single-character string: "R" for the rook, "p" for a pawn, "B" for a bishop (or any other blocking piece), and "." for an empty square. The algorithm scans the board to locate the rook, then examines the four orthogonal directions (left, right, up, down) until it either captures a pawn or encounters a blocking piece. The total number of successful captures is returned.

Locating the Rook

The outer loops iterate over every row index y and column index x. When the cell board[y][x] equals "R", the algorithm proceeds to evaluate the four directions.

for y in range(8):
    for x in range(8):
        if board[y][x] == "R":
            # direction scans start here

Because the board size is fixed, the double loop guarantees that the rook will be found in at most 64 iterations, and the inner work is only performed once.

Scanning Left

Starting from the column immediately left of the rook (x-1) and moving toward column 0, the code checks each square. If a pawn is encountered, the result counter is incremented. Regardless of whether a pawn was captured, the loop terminates as soon as a non-empty square is seen, because any further squares are blocked.

for dx in range(x - 1, -1, -1):
    if board[y][dx] == "p":
        result += 1
    if board[y][dx] != ".":
        break

Scanning Right

The rightward scan mirrors the leftward logic, advancing from x+1 up to column 7. The same early-exit condition applies.

for dx in range(x + 1, 8):
    if board[y][dx] == "p":
        result += 1
    if board[y][dx] != ".":
        break

Scanning Up

The upward direction moves from the row above the rook (y-1) toward row 0, staying in the same column x. The loop stops at the first non-empty square, capturing a pawn if present.

for dy in range(y - 1, -1, -1):
    if board[dy][x] == "p":
        result += 1
    if board[dy][x] != ".":
        break

Scanning Down

The downward scan proceeds from y+1 to row 7, applying identical capture and break logic.

for dy in range(y + 1, 8):
    if board[dy][x] == "p":
        result += 1
    if board[dy][x] != ".":
        break

Result Accumulation

Each time a pawn is found in a clear line of sight, the result variable is incremented. After all four directions have been examined, the final count is returned.

return result

Edge Cases Handled

When the rook is positioned on any edge of the board, the corresponding directional loop simply has an empty range, so no out-of-bounds access occurs. If the board contains no rook at all, the outer loops complete without ever entering the directional scans, leaving result at its initial value of 0.

The algorithm also correctly handles scenarios where a pawn is immediately adjacent to the rook; the pawn is counted and the loop breaks, preventing any further (unnecessary) checks beyond the captured piece.

If a blocking piece such as a bishop ("B" or any character other than "." or "p") lies between the rook and a pawn, the break statement stops the scan before the pawn, ensuring that only unobstructed captures are counted.

Multiple pawns aligned in the same direction are not double-counted because the scan stops after the first non-empty square, which aligns with chess rules where a rook cannot jump over pieces.

Performance Optimizations

The implementation leverages the fixed board dimensions to avoid dynamic data structures or additional memory allocation. By breaking out of each directional loop as soon as a non-empty square is encountered, the algorithm minimizes the number of cell inspections, often examining far fewer than the maximum of seven squares per direction.

Scanning stops after the rook is found, preventing redundant work on the remainder of the board. The use of simple integer ranges and direct indexing (board[y][dx] and board[dy][x]) ensures low overhead per iteration.

Overall, the code achieves a tight, constant-time execution profile suitable for the constrained 8 × 8 input space.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big square grid that looks like a chessboard with many tiny squares. Some of those squares are empty, some have little pawns waiting to be captured, and one special square has a rook piece on it. The rook is very strong and likes to move in nice straight lines.

The code starts by looking through every single square on the board to find where that rook is hiding. Once the rook is found, it sends out lookouts in four different directions: to the left, to the right, up, and down.

As the rook looks down each path, it checks every square it sees. If it spots a pawn, it adds that pawn to a count to remember it found one. But, the rook is not allowed to jump over other pieces, so if it sees a wall or another piece that is not a pawn, it stops looking in that direction and moves on to the next path. By the time the rook finishes looking in all four directions, it knows exactly how many pawns it can reach.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.15 | σ = 0.66

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
35 links | 21 authors | 9 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

1 easy
2 solutions   October 23, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality