using System;
using System.Collections.Generic;
class GfG{
// Count the number of onward valid knight moves from (x, y)
static int countOptions(int[,] board, int x, int y, int[][] dir){
int count = 0;
int n = board.GetLength(0);
// Check all 8 possible dir
for (int i = 0; i < 8; ++i)
{
int nx = x + dir[i][0];
int ny = y + dir[i][1];
// If next cell is inside grid and unvisited (represented by 0)
if (nx >= 0 && ny >= 0 && nx < n && ny < n
&& board[nx, ny] == 0)
++count;
}
return count;
}
// Generate possible knight moves from (x, y), sorted by
// least onward options
static List<int[]> getSortedMoves(int[,] board, int x, int y,
int[][] dir)
{
var moves = 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 next cell is inside grid and unvisited
if (nx >= 0 && ny >= 0 && nx < n && ny < n && board[nx, ny] == 0)
{
// Store onward move count and direction index
moves.Add(new int[] { countOptions(board, nx, ny, dir),
i });
}
}
// Sort by Warnsdorff's heuristic (fewer onward moves first)
moves.Sort((a, b) => a[0].CompareTo(b[0]));
return moves;
}
// Recursive function to explore knight's tour from (x, y)
static bool knightTourUtil(int x, int y, int step, int n, int[,] board,
int[][] dir){
if (step == n * n) return true;
List<int[]> moves = getSortedMoves(board, x, y, dir);
foreach (var move in moves){
int dirIdx = move[1];
int nx = x + dir[dirIdx][0];
int ny = y + dir[dirIdx][1];
// Make move
board[nx, ny] = step;
// Recursively try next move
if (knightTourUtil(nx, ny, step + 1, n, board, dir))
return true;
// Backtrack
board[nx, ny] = 0;
}
return false;
}
// Function to start the knight's tour
static int[,] knightTour(int n){
int[,] board = new int[n, n];
board[0, 0] = -1;
// Define all 8 possible knight moves
int[][] dir = new int[][]{
new int[]{ -2, -1 }, new int[]{ -1, -2 }, new int[]{ 1, -2 },
new int[]{ 2, -1 }, new int[]{ 2, 1 }, new int[]{ 1, 2 },
new int[]{ -1, 2 }, new int[]{ -2, 1 }
};
// Start solving from step 1
if (!knightTourUtil(0, 0, 1, n, board, dir)){
// Return {-1} if solution doesn't exist
return new int[,] { { -1 } };
}
// Mark the start position as 0
board[0, 0] = 0;
// Check if there's exactly one unvisited cell left
// (if empty cell count is 1)
int empty = 0;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
if (board[i, j] == 0) empty++;
if (empty == 1) return board;
// If there are more than one empty cells, return {-1}
// (no valid tour)
return new int[,] { { -1 } };
}
// Driver code
static void Main(){
int n = 5;
int[,] res = knightTour(n);
int rows = res.GetLength(0);
int cols = res.GetLength(1);
// Print the result board
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
Console.Write(res[i, j] + " ");
}
Console.WriteLine();
}
}
}