Check Knight Tour Configuration Problem
Description
LeetCode Problem 2596.
There is a knight on an n x n chessboard. In a valid configuration, the knight starts at the top-left cell of the board and visits every cell on the board exactly once.
You are given an n x n integer matrix grid consisting of distinct integers from the range [0, n * n - 1] where grid[row][col] indicates that the cell (row, col) is the grid[row][col]^th cell that the knight visited. The moves are 0-indexed.
Return true if grid represents a valid configuration of the knight's movements or false otherwise.
Note that a valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The figure below illustrates all the possible eight moves of a knight from some cell.

Example 1:

Input: 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]]
Output: true
Explanation: The above diagram represents the grid. It can be shown that it is a valid configuration.
Example 2:

Input: grid = [[0,3,6],[5,8,1],[2,7,4]]
Output: false
Explanation: The above diagram represents the grid. The 8^th move of the knight is not valid considering its position after the 7^th move.
Constraints:
n == grid.length == grid[i].length3 <= n <= 70 <= grid[row][col] < n * n- All integers in
gridare unique.
Solution
Approach: Simulation
Record the cell of each step in an array pos, where pos[v] is the position of the cell numbered v. The tour must start at (0, 0), so return false if grid[0][0] is not 0. Then check each pair of consecutive positions: the row and column differences must be (1, 2) or (2, 1). If every move is legal, the configuration is valid.
Complexity: time O(n^2), space O(n^2), where n is the side length of the board.
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 zip(pos, pos[1:]):
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