Advertisement
Guest User

Untitled

a guest
Jan 13th, 2019
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.99 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace KnightsTour
  6. {
  7. public class Program
  8. {
  9. private static int turns = 1;
  10. private static int[][] board;
  11.  
  12. private static Point currentPoint = new Point(0, 0);
  13. private static List<Point> candidates = new List<Point>();
  14.  
  15. public static void Main()
  16. {
  17. ReadInput();
  18. MakeTour();
  19. PrintBoard();
  20. }
  21.  
  22. private static void ReadInput()
  23. {
  24. int n = int.Parse(Console.ReadLine());
  25. board = new int[n][];
  26.  
  27. for (int i = 0; i < n; i++)
  28. {
  29. board[i] = new int[n];
  30. }
  31. }
  32.  
  33. private static void MakeTour()
  34. {
  35. candidates = FindPotentialMoves(currentPoint);
  36. board[currentPoint.Row][currentPoint.Col] = turns++;
  37.  
  38. while (candidates.Count > 0)
  39. {
  40. int minNextMoves = int.MaxValue;
  41. Point bestCandidate = null;
  42.  
  43. foreach (var candidate in candidates)
  44. {
  45. int candidateMoves = FindPotentialMoves(candidate).Count;
  46. if (candidateMoves < minNextMoves)
  47. {
  48. minNextMoves = candidateMoves;
  49. bestCandidate = candidate;
  50. }
  51. }
  52.  
  53. currentPoint = bestCandidate;
  54. board[currentPoint.Row][currentPoint.Col] = turns++;
  55. candidates = FindPotentialMoves(currentPoint);
  56. }
  57. }
  58.  
  59. private static void PrintBoard()
  60. {
  61. foreach (var row in board)
  62. {
  63. Console.WriteLine(string.Join(" ", row.Select(r => r.ToString().PadLeft(3))));
  64. }
  65. }
  66.  
  67. private static List<Point> FindPotentialMoves(Point point)
  68. {
  69. List<Point> result = new List<Point>
  70. {
  71. new Point(point.Row + 1, point.Col + 2),
  72. new Point(point.Row - 1, point.Col + 2),
  73. new Point(point.Row + 1, point.Col - 2),
  74. new Point(point.Row - 1, point.Col - 2),
  75. new Point(point.Row + 2, point.Col + 1),
  76. new Point(point.Row + 2, point.Col - 1),
  77. new Point(point.Row - 2, point.Col + 1),
  78. new Point(point.Row - 2, point.Col - 1)
  79. };
  80.  
  81. return result.Where(p => IsInBoard(p.Row, p.Col) && board[p.Row][p.Col] == 0).ToList();
  82. }
  83.  
  84. private static bool IsInBoard(int row, int col)
  85. {
  86. return 0 <= row && row < board.Length && 0 <= col && col < board[row].Length;
  87. }
  88. }
  89.  
  90. public class Point
  91. {
  92. public Point(int row, int col)
  93. {
  94. this.Row = row;
  95. this.Col = col;
  96. }
  97.  
  98. public int Row { get; set; }
  99.  
  100. public int Col { get; set; }
  101. }
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement