捕获黑皇后需要的最少移动次数
难度:
标签:
题目描述
There is a 1-indexed 8 x 8
chessboard containing 3
pieces.
You are given 6
integers a
, b
, c
, d
, e
, and f
where:
(a, b)
denotes the position of the white rook.(c, d)
denotes the position of the white bishop.(e, f)
denotes the position of the black queen.
Given that you can only move the white pieces, return the minimum number of moves required to capture the black queen.
Note that:
- Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces.
- Bishops can move any number of squares diagonally, but cannot jump over other pieces.
- A rook or a bishop can capture the queen if it is located in a square that they can move to.
- The queen does not move.
Example 1:

Input: a = 1, b = 1, c = 8, d = 8, e = 2, f = 3 Output: 2 Explanation: We can capture the black queen in two moves by moving the white rook to (1, 3) then to (2, 3). It is impossible to capture the black queen in less than two moves since it is not being attacked by any of the pieces at the beginning.
Example 2:

Input: a = 5, b = 3, c = 3, d = 4, e = 5, f = 2 Output: 1 Explanation: We can capture the black queen in a single move by doing one of the following: - Move the white rook to (5, 2). - Move the white bishop to (5, 2).
Constraints:
1 <= a, b, c, d, e, f <= 8
- No two pieces are on the same square.
代码结果
运行时间: 20 ms, 内存: 0.0 MB
/*
* Solution Approach using Java Streams:
* This solution uses Java Stream API to streamline the logic and enhance readability.
* The logic is similar to the Java solution but leverages streams for computations.
*/
import java.util.stream.IntStream;
public class ChessCaptureStream {
public int minMovesToCapture(int a, int b, int c, int d, int e, int f) {
int rookMoves = (a == e || b == f) && IntStream.range(Math.min(b, f) + 1, Math.max(b, f)).noneMatch(i -> (c == a && d == i) || (c == a && d == b))
? Math.abs(a - e) + Math.abs(b - f) : Integer.MAX_VALUE;
int delta = Math.abs(c - e);
int bishopMoves = Math.abs(c - e) == Math.abs(d - f) && IntStream.range(1, delta).noneMatch(i -> (a == c + i * (e - c) / delta && b == d + i * (f - d) / delta) || (c == c + i * (e - c) / delta && d == d + i * (f - d) / delta))
? delta : Integer.MAX_VALUE;
return Math.min(rookMoves, bishopMoves);
}
}
解释
方法:
此题解的核心思路是利用棋子的移动规则直接判断白车和白象能否直接或间接捕获黑皇后。首先检查白车是否在与黑皇后同一行或同一列上,如果是则可以直接捕获,除非白象阻挡在中间需要先移动白象。其次检查白象是否在与黑皇后同一对角线上,如果是则也可以直接捕获,除非白车阻挡在中间需要先移动白车。如果以上情况都不满足,说明至少需要两步才能捕获黑皇后。
时间复杂度:
O(1)
空间复杂度:
O(1)
代码细节讲解
🦆
该算法是如何确保白车和白象之间没有其他未提及的棋子阻挡?
▷🦆
当白车和白象都不能直接捕获黑皇后时,算法如何确定最佳的移动策略以最小化移动次数?
▷🦆
在判断白车或白象是否与黑皇后在同一行或列时,如果白车与白象在同一行或列但位置不影响捕获路径,算法是否还是返回需要两步?
▷