LeetCode 题解工作台
捕获黑皇后需要的最少移动次数
现有一个下标从 1 开始的 8 x 8 棋盘,上面有 3 枚棋子。 给你 6 个整数 a 、 b 、 c 、 d 、 e 和 f ,其中: (a, b) 表示白色车的位置。 (c, d) 表示白色象的位置。 (e, f) 表示黑皇后的位置。 假定你只能移动白色棋子,返回捕获黑皇后所需的 最少 移动次…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数学·结合·enumeration
答案摘要
根据题意,我们可以将捕获黑皇后的情况分为以下几种: 1. 白色车和黑皇后在同一行,且中间没有其他棋子,此时只需要移动白色车 一次;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·enumeration 题型思路
题目描述
现有一个下标从 1 开始的 8 x 8 棋盘,上面有 3 枚棋子。
给你 6 个整数 a 、b 、c 、d 、e 和 f ,其中:
(a, b)表示白色车的位置。(c, d)表示白色象的位置。(e, f)表示黑皇后的位置。
假定你只能移动白色棋子,返回捕获黑皇后所需的最少移动次数。
请注意:
- 车可以向垂直或水平方向移动任意数量的格子,但不能跳过其他棋子。
- 象可以沿对角线方向移动任意数量的格子,但不能跳过其他棋子。
- 如果车或象能移向皇后所在的格子,则认为它们可以捕获皇后。
- 皇后不能移动。
示例 1:
输入:a = 1, b = 1, c = 8, d = 8, e = 2, f = 3 输出:2 解释:将白色车先移动到 (1, 3) ,然后移动到 (2, 3) 来捕获黑皇后,共需移动 2 次。 由于起始时没有任何棋子正在攻击黑皇后,要想捕获黑皇后,移动次数不可能少于 2 次。
示例 2:
输入:a = 5, b = 3, c = 3, d = 4, e = 5, f = 2 输出:1 解释:可以通过以下任一方式移动 1 次捕获黑皇后: - 将白色车移动到 (5, 2) 。 - 将白色象移动到 (5, 2) 。
提示:
1 <= a, b, c, d, e, f <= 8- 两枚棋子不会同时出现在同一个格子上。
解题思路
方法一:分类讨论
根据题意,我们可以将捕获黑皇后的情况分为以下几种:
- 白色车和黑皇后在同一行,且中间没有其他棋子,此时只需要移动白色车 一次;
- 白色车和黑皇后在同一列,且中间没有其他棋子,此时只需要移动白色车 一次;
- 白色象和黑皇后在对角线
\上,且中间没有其他棋子,此时只需要移动白色象 一次; - 白色象和黑皇后在对角线
/上,且中间没有其他棋子,此时只需要移动白色象 一次; - 其他情况,只需要移动两次。
时间复杂度 ,空间复杂度 。
class Solution:
def minMovesToCaptureTheQueen(
self, a: int, b: int, c: int, d: int, e: int, f: int
) -> int:
if a == e and (c != a or (d - b) * (d - f) > 0):
return 1
if b == f and (d != b or (c - a) * (c - e) > 0):
return 1
if c - e == d - f and (a - e != b - f or (a - c) * (a - e) > 0):
return 1
if c - e == f - d and (a - e != f - b or (a - c) * (a - e) > 0):
return 1
return 2
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on enumerating all reachable squares for both white pieces and evaluating attack paths, which is bounded by the fixed 8x8 board. Space complexity is minimal, storing positions and sequences for analysis. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can you determine if a single move capture is possible?
- question_mark
How do you enumerate all reachable squares for the rook and bishop efficiently?
- question_mark
What is the strategy to minimize moves when direct capture is blocked?
常见陷阱
外企场景- error
Forgetting the board is 1-indexed, causing off-by-one errors in position checks.
- error
Overlooking diagonal paths for the bishop when enumerating potential moves.
- error
Assuming capture always takes two moves without checking immediate alignment opportunities.
进阶变体
外企场景- arrow_right_alt
Change board size to NxN and analyze minimum moves using the same enumeration strategy.
- arrow_right_alt
Include additional white pieces and determine the fewest moves using multiple piece types.
- arrow_right_alt
Require capturing multiple black pieces, extending the enumeration pattern to sequences of attacks.