mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-23 12:35:55 +08:00
@ -4,9 +4,10 @@ import java.util.*;
|
||||
|
||||
/*
|
||||
* Problem Statement: -
|
||||
|
||||
Given a N*N board with the Knight placed on the first block of an empty board. Moving according to the rules of
|
||||
chess knight must visit each square exactly once. Print the order of each cell in which they are visited.
|
||||
|
||||
Given a N*N board with the Knight placed on the first block of an empty board. Moving according
|
||||
to the rules of chess knight must visit each square exactly once. Print the order of each cell in
|
||||
which they are visited.
|
||||
|
||||
Example: -
|
||||
|
||||
@ -27,14 +28,14 @@ public class KnightsTour {
|
||||
|
||||
private static final int base = 12;
|
||||
private static final int[][] moves = {
|
||||
{ 1, -2 },
|
||||
{ 2, -1 },
|
||||
{ 2, 1 },
|
||||
{ 1, 2 },
|
||||
{ -1, 2 },
|
||||
{ -2, 1 },
|
||||
{ -2, -1 },
|
||||
{ -1, -2 },
|
||||
{1, -2},
|
||||
{2, -1},
|
||||
{2, 1},
|
||||
{1, 2},
|
||||
{-1, 2},
|
||||
{-2, 1},
|
||||
{-2, -1},
|
||||
{-1, -2},
|
||||
}; // Possible moves by knight on chess
|
||||
private static int[][] grid; // chess grid
|
||||
private static int total; // total squares in chess
|
||||
@ -75,23 +76,17 @@ public class KnightsTour {
|
||||
return false;
|
||||
}
|
||||
|
||||
Collections.sort(
|
||||
neighbor,
|
||||
new Comparator<int[]>() {
|
||||
public int compare(int[] a, int[] b) {
|
||||
return a[2] - b[2];
|
||||
}
|
||||
Collections.sort(neighbor, new Comparator<int[]>() {
|
||||
public int compare(int[] a, int[] b) {
|
||||
return a[2] - b[2];
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
for (int[] nb : neighbor) {
|
||||
row = nb[0];
|
||||
column = nb[1];
|
||||
grid[row][column] = count;
|
||||
if (
|
||||
!orphanDetected(count, row, column) &&
|
||||
solve(row, column, count + 1)
|
||||
) {
|
||||
if (!orphanDetected(count, row, column) && solve(row, column, count + 1)) {
|
||||
return true;
|
||||
}
|
||||
grid[row][column] = 0;
|
||||
@ -109,7 +104,7 @@ public class KnightsTour {
|
||||
int y = m[1];
|
||||
if (grid[row + y][column + x] == 0) {
|
||||
int num = countNeighbors(row + y, column + x);
|
||||
neighbour.add(new int[] { row + y, column + x, num });
|
||||
neighbour.add(new int[] {row + y, column + x, num});
|
||||
}
|
||||
}
|
||||
return neighbour;
|
||||
|
Reference in New Issue
Block a user