[LeetCode] Check Knight Tour Configuration

2596. Check Knight Tour Configuration

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
bool checkValidGrid(vector<vector<int>>& A) {
int dy[8]{-1,-2,-2,-1,1,2,2,1},dx[8]{-2,-1,1,2,2,1,-1,-2};
int y = 0, x = 0, n = A.size();
if(A[y][x]) return false;
for(int i = 0; i < n * n - 1; i++) {
bool ok = false;
for(int j = 0; j < 8 and !ok; j++) {
int ny = y + dy[j], nx = x + dx[j];
if(0 <= ny and ny < n and 0 <= nx and nx < n) {
if(A[y][x] + 1 == A[ny][nx]) {
y = ny, x = nx, ok = true;
}
}
}
if(!ok) return false;
}
return true;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/03/19/PS/LeetCode/check-knight-tour-configuration/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.