Advertisement
vencinachev

TheKnightTour

Sep 25th, 2022
833
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.22 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Backtracking_TKT
  8. {
  9.     class Program
  10.     {
  11.         static int N;
  12.  
  13.         static bool IsSafe(int[,] board, int row, int col)
  14.         {
  15.             if (row < 0 || col < 0 || row >= N || col >= N)
  16.             {
  17.                 return false;
  18.             }
  19.             if (board[row, col] != 0)
  20.             {
  21.                 return false;
  22.             }
  23.             return true;
  24.         }
  25.  
  26.         static void PrintSolution(int[,] board)
  27.         {
  28.             for (int i = 0; i < N; i++)
  29.             {
  30.                 for (int j = 0; j < N; j++)
  31.                 {
  32.                     Console.Write("{0:00} ", board[i, j]);
  33.                 }
  34.                 Console.WriteLine();
  35.             }
  36.         }
  37.  
  38.         static bool SolveKnightTour(int[,] board, int x, int y, int movei, int[] xMove, int[] yMove)
  39.         {
  40.             if ((movei - 1) == N * N)
  41.             {
  42.                 return true;
  43.             }
  44.             for (int k = 0; k < 8; k++)
  45.             {
  46.                 int nextX = x + xMove[k];
  47.                 int nextY = y + yMove[k];
  48.                 if (IsSafe(board, nextX, nextY))
  49.                 {
  50.                     board[nextX, nextY] = movei;
  51.                     //PrintSolution(board);
  52.                     //Console.WriteLine();
  53.                     if (SolveKnightTour(board, nextX, nextY, movei + 1, xMove, yMove))
  54.                     {
  55.                         return true;
  56.                     }
  57.                     else
  58.                     {
  59.                         board[nextX, nextY] = 0;
  60.                     }
  61.                 }
  62.             }
  63.             return false;
  64.         }
  65.         static void Main(string[] args)
  66.         {
  67.             N = 6;
  68.             int[,] matrix = new int[N, N];
  69.             int[] xm = { -1, -1, 1, 1, -2, -2, 2, 2 };
  70.             int[] ym = { -2, 2, 2, -2, 1, -1, 1, -1 };
  71.             if (!SolveKnightTour(matrix, 0, 0, 1, xm, ym))
  72.             {
  73.                 Console.WriteLine("No solution!");
  74.             }
  75.             else
  76.             {
  77.                 PrintSolution(matrix);
  78.             }
  79.         }
  80.     }
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement