骑士从 0 号格子出发,依次遍历到 n * n - 1 号格子才停止,由于棋盘上已经标注好了骑士巡视时每个格子的序号,因此我们可以使用一个哈希表,把格子的序号,以及对应的坐标存进去。这样在遍历棋盘的过程中,只需要找到下一个格子的位置,然后判断下一个格子的位置和当前的位置是否满足题目的条件(日字)。
需要注意的是,题目要求,合法的路线必须从左上角开始,因此,当(0,0)号格子的序号不是 0,那么这个棋盘上肯定没有一个合法的遍历路线。
class Solution {
public boolean checkValidGrid(int[][] grid) {
int n = grid.length;
Map<Integer, int[]> num2pos = new HashMap<>();
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
num2pos.put(grid[i][j], new int[]{i, j});
}
}
int[] startPos = num2pos.get(0);
int x = startPos[0], y = startPos[1];
if (x != 0 || y != 0) {
return false;
}
for (int i = 1; i < n * n; ++i) {
int[] pos = num2pos.get(i);
if (!validPos(pos, x, y)) {
return false;
}
x = pos[0];
y = pos[1];
}
return true;
}
private boolean validPos(int[] nextPos, int curX, int curY) {
int x = nextPos[0];
int y = nextPos[1];
return (Math.abs(x - curX) == 2 && Math.abs(y - curY) == 1) || (Math.abs(x - curX) == 1 && Math.abs(y - curY) == 2);
}
}
- 时间复杂度:O(n^2),因为需要遍历
n * n个格子 - 空间复杂度:O(n^2),因为需要保存
n * n个格子的坐标