LeetCode 2596: Check Knight Tour Configuration Solution

Master LeetCode problem 2596 (Check Knight Tour Configuration), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2596. Check Knight Tour Configuration

Problem Explanation

Explanation

To solve this problem, we need to check if the given grid represents a valid knight's tour configuration. We can do this by iterating through each cell in the grid and verifying if the knight's moves are valid according to the rules of a knight's move on a chessboard.

We will start by checking if the knight's move from the current cell to the next cell is valid. If all moves are valid and the knight visits every cell exactly once, we return true; otherwise, we return false.

Time complexity: O(n^2) where n is the size of the grid Space complexity: O(n^2) for the visited array

Solution Code

class Solution {
    public boolean isKnightTour(int[][] grid) {
        int n = grid.length;
        int[][] moves = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}};
        boolean[][] visited = new boolean[n][n];

        int row = 0;
        int col = 0;
        visited[row][col] = true;

        for (int i = 1; i < n * n; i++) {
            boolean found = false;
            for (int[] move : moves) {
                int newRow = row + move[0];
                int newCol = col + move[1];
                if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < n && !visited[newRow][newCol] && grid[newRow][newCol] == i) {
                    visited[newRow][newCol] = true;
                    row = newRow;
                    col = newCol;
                    found = true;
                    break;
                }
            }
            if (!found) {
                return false;
            }
        }

        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2596 (Check Knight Tour Configuration)?

This page provides optimized solutions for LeetCode problem 2596 (Check Knight Tour Configuration) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2596 (Check Knight Tour Configuration)?

The time complexity for LeetCode 2596 (Check Knight Tour Configuration) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2596 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2596 in Java, C++, or Python.

Back to LeetCode Solutions