import java.util.
Scanner;
public class Main {
// Check if a knight can be placed at position (x, y) on the board
static boolean isSafe(int x, int y, int N, int sol[][]) {
return (x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1);
}
// Print the solution matrix
static void printSolution(int sol[][]) {
for (int x = 0; x < sol.length; x++) {
for (int y = 0; y < sol.length; y++)
System.out.print(sol[x][y] + " ");
System.out.println();
}
}
// Solve the Knight's Tour Problem using backtracking
static boolean solveKT(int N) {
// Initialize an empty solution matrix
int sol[][] = new int[N][N];
// Fill the matrix with -1 to indicate unvisited cells
for (int x = 0; x < N; x++)
for (int y = 0; y < N; y++)
sol[x][y] = -1;
// Define the possible moves of a knight
int xMove[] = {2, 1, -1, -2, -2, -1, 1, 2};
int yMove[] = {1, 2, 2, 1, -1, -2, -2, -1};
// Set the starting position to (0, 0) and mark it as visited
sol[0][0] = 0;
// Call the recursive helper function to find the solution
if (!solveKTUtil(0, 0, 1, sol, xMove, yMove, N)) {
System.out.println("No solution exists");
return false;
} else
printSolution(sol);
return true;
}
// Recursive helper function to solve the Knight's Tour Problem
static boolean solveKTUtil(int x, int y, int movei, int sol[][], int xMove[],
int yMove[], int N) {
int k, next_x, next_y;
// Base case: if all squares are visited, return true
if (movei == N * N)
return true;
// Try all possible moves from the current position
for (k = 0; k < 8; k++) {
// Get the next position of the knight
next_x = x + xMove[k];
next_y = y + yMove[k];
// Check if the next position is safe and not visited
if (isSafe(next_x, next_y, N, sol)) {
// Mark the next position as visited
sol[next_x][next_y] = movei;
// Recursively check if this move leads to a solution
if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove, N))
return true;
else
// If not, backtrack and unmark the position
sol[next_x][next_y] = -1;
}
}
// If none of the moves work, return false
return false;
}
// Driver code
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the chessboard: ");
int size = scanner.nextInt();
// Call the solveKT method with the dynamically input size
solveKT(size);
scanner.close();
}
}