0% found this document useful (0 votes)
70 views2 pages

Knight's Tour

This Java code is solving the Knight's Tour problem of finding a path that allows a knight to visit every square on a chessboard exactly once. It uses backtracking recursion to iteratively place the knight on valid squares based on knight move rules, tracking the path in a 2D array. If a complete valid path is found, the solution is printed; otherwise it returns that no solution exists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views2 pages

Knight's Tour

This Java code is solving the Knight's Tour problem of finding a path that allows a knight to visit every square on a chessboard exactly once. It uses backtracking recursion to iteratively place the knight on valid squares based on knight move rules, tracking the path in a 2D array. If a complete valid path is found, the solution is printed; otherwise it returns that no solution exists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.util.

Scanner;

public class Main {


static boolean isSafe(int x, int y, int N, int sol[][]) {
return (x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1);
}

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();
}
}

static boolean solveKT(int N) {


int sol[][] = new int[N][N];

for (int x = 0; x < N; x++)


for (int y = 0; y < N; y++)
sol[x][y] = -1;

int xMove[] = {2, 1, -1, -2, -2, -1, 1, 2};


int yMove[] = {1, 2, 2, 1, -1, -2, -2, -1};

sol[0][0] = 0;

if (!solveKTUtil(0, 0, 1, sol, xMove, yMove, N)) {


System.out.println("No solution exists");
return false;
} else
printSolution(sol);

return true;
}

static boolean solveKTUtil(int x, int y, int movei, int sol[][], int xMove[],
int yMove[], int N) {
int k, next_x, next_y;
if (movei == N * N)
return true;

for (k = 0; k < 8; k++) {


next_x = x + xMove[k];
next_y = y + yMove[k];
if (isSafe(next_x, next_y, N, sol)) {
sol[next_x][next_y] = movei;
if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove, N))
return true;
else
sol[next_x][next_y] = -1;
}
}

return false;
}

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();
solveKT(size);
scanner.close();
}
}

You might also like