LeetCode 题解工作台
检查骑士巡视方案
骑士在一张 n x n 的棋盘上巡视。在 有效 的巡视方案中,骑士会从棋盘的 左上角 出发,并且访问棋盘上的每个格子 恰好一次 。 给你一个 n x n 的整数矩阵 grid ,由范围 [0, n * n - 1] 内的不同整数组成,其中 grid[row][col] 表示单元格 (row, col…
5
题型
5
代码语言
3
相关题
当前训练重点
中等 · 图·搜索
答案摘要
我们先用数组 记录骑士访问的每个格子的坐标,然后遍历 数组,检查相邻两个格子的坐标差是否为 $(1, 2)$ 或 $(2, 1)$ 即可。若不满足,则返回 。 否则遍历结束后,返回
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路
题目描述
骑士在一张 n x n 的棋盘上巡视。在 有效 的巡视方案中,骑士会从棋盘的 左上角 出发,并且访问棋盘上的每个格子 恰好一次 。
给你一个 n x n 的整数矩阵 grid ,由范围 [0, n * n - 1] 内的不同整数组成,其中 grid[row][col] 表示单元格 (row, col) 是骑士访问的第 grid[row][col] 个单元格。骑士的行动是从下标 0 开始的。
如果 grid 表示了骑士的有效巡视方案,返回 true;否则返回 false。
注意,骑士行动时可以垂直移动两个格子且水平移动一个格子,或水平移动两个格子且垂直移动一个格子。下图展示了骑士从某个格子出发可能的八种行动路线。

示例 1:
输入:grid = [[0,11,16,5,20],[17,4,19,10,15],[12,1,8,21,6],[3,18,23,14,9],[24,13,2,7,22]] 输出:true 解释:grid 如上图所示,可以证明这是一个有效的巡视方案。
示例 2:
输入:grid = [[0,3,6],[5,8,1],[2,7,4]] 输出:false 解释:grid 如上图所示,考虑到骑士第 7 次行动后的位置,第 8 次行动是无效的。
提示:
n == grid.length == grid[i].length3 <= n <= 70 <= grid[row][col] < n * ngrid中的所有整数 互不相同
解题思路
方法一:模拟
我们先用数组 记录骑士访问的每个格子的坐标,然后遍历 数组,检查相邻两个格子的坐标差是否为 或 即可。若不满足,则返回 。
否则遍历结束后,返回
时间复杂度 ,空间复杂度 。其中 为棋盘的边长。
class Solution:
def checkValidGrid(self, grid: List[List[int]]) -> bool:
if grid[0][0]:
return False
n = len(grid)
pos = [None] * (n * n)
for i in range(n):
for j in range(n):
pos[grid[i][j]] = (i, j)
for (x1, y1), (x2, y2) in pairwise(pos):
dx, dy = abs(x1 - x2), abs(y1 - y2)
ok = (dx == 1 and dy == 2) or (dx == 2 and dy == 1)
if not ok:
return False
return True
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidates may struggle with efficiently verifying valid moves in a DFS traversal.
- question_mark
Be aware of performance concerns for larger grid sizes (n=7).
- question_mark
Look for clear understanding of knight’s L-shaped movement and boundary validation.
常见陷阱
外企场景- error
Overlooking the knight's movement pattern can lead to incorrect configurations.
- error
Failing to track visited cells or revisiting a cell can result in an invalid configuration.
- error
Misunderstanding the bounds of the grid could cause out-of-bound errors or incorrect results.
进阶变体
外企场景- arrow_right_alt
Change the board size to test efficiency across different n values.
- arrow_right_alt
Modify the starting position of the knight to test other valid configurations.
- arrow_right_alt
Add a constraint where the knight moves in a more complex pattern.