A Poor King
Time limit5sMemory limit256 MB
Given a black king and two white pieces (rook, bishop, or queen) on an 8x8 board, find the fewest White moves that force checkmate, or 0 if it cannot be forced.
- Level
Medium7 of 10
- Topics
- BFS, Graph, Simulation
- Solved
- No attempts yet
Problem
There are two white pieces and one black king on a chess board. Each white piece is a rook, a bishop, or a queen. It is White's turn to move. You play for White and must checkmate the black king in as few moves as possible. Assuming Black plays the best possible strategy to prolong the game, write a program that finds the minimum number of moves White needs to checkmate.
Rules of chess used in this problem:
- This position is not legal in chess because there is no white king on the board. Otherwise, the game follows the standard chess rules.
- The board is squares. The columns are labeled
atoh, and the rows are labeled1to8. - The players alternate moves, each moving one piece of their own color. This problem counts only moves made by White.
- A rook moves horizontally or vertically through any number of empty squares. It cannot jump over a piece of its own color or stop on a square occupied by one.
- A bishop moves diagonally through any number of empty squares. It cannot jump over a piece of its own color or stop on a square occupied by one.
- A queen moves horizontally, vertically, or diagonally through any number of empty squares. It cannot jump over a piece of its own color or stop on a square occupied by one.
- A check is a threat to capture the king on the next move.
- A king moves one square in any direction. It cannot move into a square that puts it in check. If that condition holds, the king may capture a white piece on an adjacent square, and the captured piece is removed from play.
- Checkmate is a position where the king is in check and has no legal move to escape.
- Stalemate is a position where the side to move is not in check but has no legal move. In chess, stalemate is a draw, which is not acceptable for White.
Input
The first line contains the number of positions, which is at most . Each following line describes one position with the locations of three pieces: the black king first, then the two white pieces. Each white piece is preceded by a letter for its type: R for rook, B for bishop, and Q for queen.
It is guaranteed that no two pieces occupy the same square and that the black king is not in check in the initial position. Otherwise, a position can be arbitrary. For example, both white pieces may be queens.
Output
For each position, print one line with the minimum number of moves White needs to guarantee checkmate from that position. If the goal cannot be reached, print 0.