Leetcode 2596: Check Knight Tour Configuration

grid47
grid47
Exploring patterns and algorithms
Feb 21, 2024 6 min read

Given an n x n chessboard, the knight starts at the top-left corner and visits every cell exactly once. The knight’s movements are represented by a grid where grid[row][col] indicates the order of the knight’s visit to that cell. Determine if this sequence of moves is valid, i.e., the knight moves according to its legal movement pattern.
Problem
Approach
Steps
Complexity
Input: The input consists of an `n x n` integer matrix `grid` where each element indicates the order of the knight's visit to the corresponding cell.
Example: For `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]]`.
Constraints:
• 3 <= n <= 7
• grid[row][col] represents a unique visit number from 0 to n*n - 1.
Output: Return `true` if the grid represents a valid sequence of knight moves, otherwise return `false`.
Example: For the 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]]`, the output should be `true`.
Constraints:
• The output will be a boolean value, either `true` or `false`.
Goal: To check if the knight’s movement follows its allowed movement rules in the given sequence.
Steps:
• 1. Create a map to store the positions of each visit from the grid.
• 2. Ensure the knight starts at the top-left corner (0, 0).
• 3. Check the movement from each cell to the next one in the grid to ensure it's a valid knight's move.
• 4. Return `true` if all moves are valid; otherwise, return `false`.
Goal: The value of `n` (board size) will always be between 3 and 7, inclusive. The grid will always have distinct integers representing the knight’s visit order.
Steps:
• 3 <= n <= 7
• Each element in `grid` will be unique and represent a valid knight's move index.
Assumptions:
• The knight’s movement follows standard rules: it moves in an L-shape: 2 squares in one direction and 1 square in a perpendicular direction.
Input: For `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]]`
Explanation: This is a valid configuration as all knight moves follow the allowed L-shape movement. The knight correctly moves from each cell to the next in the sequence.

Input: For `grid = [[0, 3, 6], [5, 8, 1], [2, 7, 4]]`
Explanation: This is not a valid configuration because the 8th move is not a valid knight move from the 7th move's position.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus