Program.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. namespace D24._1
  6. {
  7. public class Program
  8. {
  9. public static int Solve(bool[][] map, (int, int) start, (int, int) goal)
  10. {
  11. var queue = new Queue<((int x, int y) coord, int steps)>();
  12. HashSet<(int, int)> visited = new HashSet<(int, int)>();
  13. queue.Enqueue((start, 0));
  14. while (queue.Count > 0)
  15. {
  16. var (coord, steps) = queue.Dequeue();
  17. if (coord == goal)
  18. return steps;
  19. foreach ((int mx, int my) in Move)
  20. {
  21. (int x, int y) ncoord = (coord.x + mx, coord.y + my);
  22. if (map[ncoord.y][ncoord.x]) continue;
  23. if (visited.Contains(ncoord)) continue;
  24. visited.Add(ncoord);
  25. queue.Enqueue((ncoord, steps + 1));
  26. }
  27. }
  28. throw new Exception();
  29. }
  30. static readonly (int mx, int my)[] Move = new[] { (-1, 0), (0, -1), (1, 0), (0, 1) };
  31. static void Main(string[] args)
  32. {
  33. var file = File.ReadAllText(args[0]).Split(new[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
  34. var poi = new Dictionary<int, (int x, int y)>();
  35. var map = ParseMap(file, poi);
  36. var perm = GetPermutations(poi.Keys.OrderBy(p => p).Skip(1), poi.Count - 1);
  37. int minStep = int.MaxValue;
  38. foreach (var p in perm)
  39. {
  40. var current = 0;
  41. int step = 0;
  42. foreach (var destination in p)
  43. {
  44. step += Solve(map, poi[current], poi[destination]);
  45. current = destination;
  46. }
  47. if (step < minStep) minStep = step;
  48. }
  49. Console.WriteLine($"The answer is : {minStep}");
  50. }
  51. public static bool[][] ParseMap(string[] file, Dictionary<int, (int x, int y)> poi)
  52. {
  53. bool[][] map = new bool[file.Length][];
  54. int l = 0;
  55. foreach (string line in file)
  56. {
  57. map[l] = new bool[line.Length];
  58. for (var i = 0; i < line.Length; ++i)
  59. {
  60. if (line[i] >= '0' && line[i] <= '9') poi.Add(line[i] - '0', (i, l));
  61. map[l][i] = line[i] == '#';
  62. }
  63. l++;
  64. }
  65. return map;
  66. }
  67. public static IEnumerable<IEnumerable<int>> GetPermutations(IEnumerable<int> list, int length)
  68. {
  69. if (length == 1) return list.Select(t => new [] { t });
  70. return GetPermutations(list, length - 1).SelectMany(t => list.Where(e => !t.Contains(e)),
  71. (t1, t2) => t1.Concat(new [] { t2 }));
  72. }
  73. }
  74. }