using System;
using System.Collections.Generic;
class GFG {
// Define 8 knight moves globally
static int[,] dir = {
{2, 1}, {1, 2}, {-1, 2}, {-2, 1},
{-2, -1}, {-1, -2}, {1, -2}, {2, -1}
};
// Count the number of onward moves from position (x, y)
static int countOptions(int[,] board, int x, int y) {
int count = 0, n = board.GetLength(0);
for (int i = 0; i < 8; i++) {
int nx = x + dir[i, 0];
int ny = y + dir[i, 1];
if (nx >= 0 && ny >= 0 && nx < n && ny < n && board[nx, ny] == -1)
count++;
}
return count;
}
// Generate valid knight moves from (x, y), sorted by fewest onward moves
static List<int[]> getSortedMoves(int[,] board, int x, int y) {
List<int[]> moveList = new List<int[]>();
int n = board.GetLength(0);
for (int i = 0; i < 8; i++) {
int nx = x + dir[i, 0];
int ny = y + dir[i, 1];
if (nx >= 0 && ny >= 0 && nx < n && ny < n && board[nx, ny] == -1) {
int options = countOptions(board, nx, ny);
moveList.Add(new int[]{options, i});
}
}
moveList.Sort((a, b) => a[0] != b[0] ?
a[0].CompareTo(b[0]) : a[1].CompareTo(b[1]));
return moveList;
}
// Recursive function to solve the Knight's Tour
static bool knightTourUtil(int x, int y, int step, int n, int[,] board) {
if (step == n * n) return true;
List<int[]> moves = getSortedMoves(board, x, y);
foreach (var move in moves) {
int dirIdx = move[1];
int nx = x + dir[dirIdx, 0];
int ny = y + dir[dirIdx, 1];
board[nx, ny] = step;
if (knightTourUtil(nx, ny, step + 1, n, board))
return true;
// Backtrack
board[nx, ny] = -1;
}
return false;
}
// Function to start Knight's Tour
static List<List<int>> knightTour(int n) {
int[,] board = new int[n, n];
List<List<int>> res = new List<List<int>>();
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
board[i, j] = -1;
board[0, 0] = 0;
if (knightTourUtil(0, 0, 1, n, board)) {
for (int i = 0; i < n; i++) {
List<int> rowList = new List<int>();
for (int j = 0; j < n; j++)
rowList.Add(board[i, j]);
res.Add(rowList);
}
return res;
}
res.Add(new List<int>{-1});
return res;
}
public static void Main() {
int n = 5;
List<List<int>> result = knightTour(n);
foreach (var row in result) {
Console.WriteLine(string.Join(" ", row));
}
}
}