using
System;
class
GFG {
static
int
[] DirX = { 2, 1, -1, -2, -2, -1, 1, 2 };
static
int
[] DirY = { 1, 2, 2, 1, -1, -2, -2, -1 };
static
bool
isSafe(
int
i,
int
j,
int
n,
int
[, ] Board)
{
return
(i >= 0 && j >= 0 && i < n && j < n
&& Board[i, j] == 0);
}
static
bool
isPossible =
false
;
static
void
knightTour(
int
[, ] ChessBoard,
int
N,
int
x,
int
y,
int
visited = 1)
{
ChessBoard[x, y] = visited;
if
(visited == N * N) {
isPossible =
true
;
for
(
int
i = 0; i < N; i++) {
for
(
int
j = 0; j < N; j++) {
Console.Write(ChessBoard[i, j] +
" "
);
}
Console.WriteLine();
}
Console.WriteLine();
ChessBoard[x, y] = 0;
return
;
}
for
(
int
i = 0; i < 8; i++) {
int
newX = x + DirX[i];
int
newY = y + DirY[i];
if
(isSafe(newX, newY, N, ChessBoard)
&& ChessBoard[newX, newY] == 0) {
knightTour(ChessBoard, N, newX, newY,
visited + 1);
}
}
ChessBoard[x, y] = 0;
}
public
static
void
Main()
{
int
[, ] ChessBoard =
new
int
[5, 5];
int
N = ChessBoard.GetLength(0);
int
X = 1;
int
Y = 1;
knightTour(ChessBoard, N, X - 1, Y - 1);
if
(isPossible ==
false
) {
Console.WriteLine(-1);
}
}
}