Check Knight Tour Configuration - Problem

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: A valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically.

Input & Output

Example 1 — Valid Knight Tour
$ 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
💡 Note: The knight starts at (0,0) with move 0, then follows valid knight moves through all positions: 0→1→2→3...→24, visiting each cell exactly once.
Example 2 — Invalid Knight Tour
$ Input: grid = [[0,3,6],[5,8,1],[2,7,4]]
Output: false
💡 Note: The knight starts at (0,0) with move 0, but move 1 is at position (2,1). A knight cannot move from (0,0) to (2,1) in one valid L-shaped move.
Example 3 — Wrong Starting Position
$ Input: grid = [[1,0],[2,3]]
Output: false
💡 Note: Move 0 should start at top-left (0,0), but here it's at (0,1). Invalid tour configuration.

Constraints

  • n == grid.length == grid[i].length
  • 3 ≤ n ≤ 7
  • 0 ≤ grid[row][col] < n * n
  • All integers in grid are unique

Visualization

Tap to expand
Knight Tour Validation: Check Valid L-shaped Moves072516438Knight Move Validation:• Move 0 at (0,0) - Start position ✓• Move 1 at (1,1) - Invalid knight move ✗• Knight moves in L-shape: ±2,±1 or ±1,±2• From (0,0) valid moves: (1,2), (2,1), etc.• But (0,0) → (1,1) is diagonal - not L-shaped!Result: false (Invalid Knight Tour)Knight must move in L-shape: 2 squares in one direction + 1 square perpendicular
Understanding the Visualization
1
Input Grid
Grid with move numbers 0 to n²-1
2
Map Positions
Create move number → position mapping
3
Validate Moves
Check each consecutive pair forms valid knight move
Key Takeaway
🎯 Key Insight: Map move numbers to positions, then validate each consecutive move follows the knight's L-shaped movement pattern
Asked in
Google 15 Meta 12 Amazon 8
12.0K Views
Medium Frequency
~15 min Avg. Time
542 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen