Check Knight Tour Configuration — LeetCode 2596 Python Solution

MediumDepth-First SearchBreadth-First SearchArrayMatrixSimulation
Problem
#2596
Reading time
3 min

The 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.

Example

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.

Python solution

Python
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 pairwise(pos):
            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

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n^2) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2596. Check Knight Tour Configuration is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2596. Check Knight Tour Configuration?
LeetCode 2596. Check Knight Tour Configuration is rated Medium on LeetCode.
What is the time complexity of LeetCode 2596. Check Knight Tour Configuration?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 2596. Check Knight Tour Configuration?
The Python solution on this page uses O(n^2) auxiliary space.
What topics does LeetCode 2596. Check Knight Tour Configuration cover?
LeetCode 2596. Check Knight Tour Configuration is tagged Depth-First Search, Breadth-First Search, Array, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview