krasi1105

Travelling Salesman polynomial solution

Dec 9th, 2017
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.01 KB | None | 0 0
  1. using System;
  2.  
  3. public class Program
  4. {
  5.     private const int LineCount = 16;
  6.     private const int NodeCount = 9;
  7.     private static int[][] nodeToNode = new int[NodeCount][];
  8.     private static int[][] nodeVisiting = new int[NodeCount][];
  9.     private static bool[] visited = new bool[LineCount];
  10.     public static void Main()
  11.     {
  12.         InitLines();
  13.         FindSolution();
  14.     }
  15.  
  16.     private static void FindSolution()
  17.     {
  18.         for (int i = 0; i < NodeCount; i++)
  19.         {
  20.             TryFindSolution(i, 0);
  21.         }
  22.         Console.WriteLine("No solution.");
  23.     }
  24.  
  25.     private static void TryFindSolution(int at, int n)
  26.     {
  27.         if (n == LineCount)
  28.         {
  29.             Console.WriteLine("Success!");
  30.         }
  31.         var arr = nodeToNode[at];
  32.         for (int i = 0; i < arr.Length; i++)
  33.         {
  34.             int n2 = arr[i];
  35.             int visiting = nodeVisiting[at][i];
  36.             if (!visited[visiting])
  37.             {
  38.                 visited[visiting] = true;
  39.                 TryFindSolution(n2, n + 1);
  40.                 visited[visiting] = false;
  41.             }
  42.         }
  43.     }
  44.  
  45.     private static void InitLines()
  46.     {
  47.         nodeVisiting[0] = new[] { 0, 2 };
  48.         nodeToNode[0] = new[] { 1, 3 };
  49.         nodeVisiting[1] = new[] { 0, 1, 3, 4, 5 };
  50.         nodeToNode[1] = new[] { 0, 2, 3, 4, 5 };
  51.         nodeVisiting[2] = new[] { 1, 6 };
  52.         nodeToNode[2] = new[] { 1, 5 };
  53.         nodeVisiting[3] = new[] { 2, 3, 7, 9, 10 };
  54.         nodeToNode[3] = new[] { 0, 1, 4, 6, 7 };
  55.         nodeVisiting[4] = new[] { 4, 7, 8, 11 };
  56.         nodeToNode[4] = new[] { 1, 3, 5, 7 };
  57.         nodeVisiting[5] = new[] { 5, 6, 8, 12, 13 };
  58.         nodeToNode[5] = new[] { 1, 2, 4, 7, 8 };
  59.         nodeVisiting[6] = new[] { 9, 14 };
  60.         nodeToNode[6] = new[] { 3, 7 };
  61.         nodeVisiting[7] = new[] { 10, 11, 12, 14, 15 };
  62.         nodeToNode[7] = new[] { 3, 4, 5, 6, 8 };
  63.         nodeVisiting[8] = new[] { 13, 15 };
  64.         nodeToNode[8] = new[] { 5, 7 };
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment