90 likes | 371 Views
Greedy TSP in C#. Data Structures for Greedy TSP. public static int [,] M; // distance matrix public static int n; // number of cities public static string [] L; // city name list public static bool [] used; // available cities
E N D
Greedy TSP in C#
Data Structures for Greedy TSP publicstaticint[,] M; // distance matrix publicstaticint n; // number of cities publicstaticstring[] L; // city name list publicstaticbool[] used; // available cities publicstaticint[] itour; // index list of cities in tour publicstaticstring[] tour; // list of cities in tour publicstaticint k; // index of next avail in tour publicstaticintistart; // index of starting city
Completing the Array Declarations // creates access to the text file Console.Write("Enter file name..."); fname = Console.ReadLine(); TextReader tr = newStreamReader(fname); // reads n = number of cities n = Convert.ToInt32(tr.ReadLine()); // declares arrays of the proper size M = newint[n, n]; L = newstring[n]; // reads city name from next line of text file // names are loaded into string array L j = 0; textline = tr.ReadLine(); foreach (string f in textline.Split(' ')) if (f != "") { L[j] = f; j += 1; }
Loading a 2D Array // reads distances between cities & loads matrix M for (int i = 0; i < n; i++) { textline = tr.ReadLine(); j = 0; foreach (string d in textline.Split(' ')) { if (d != "") { M[i, j] = Convert.ToInt32(d); j += 1; } } } // close the access to text file tr.Close(); }
Initializing a Run of Greedy TSP used = newbool[n]; itour = newint[n]; tour = newstring[n]; for (int i = 0; i < n; i++) { used[i] = false; itour[i] = -1; tour[i] = ""; } // get the index, p of starting city from user itour[k] = p; tour[k] = L[p]; used[itour[k]] = true; k += 1;
Finding the Closest Available Next City publicstaticint minAvail(int row) { int minval = int.MaxValue; int imin = -1; for (int j = 0; j < n; j++) { if (row != j && !used[j] && M[row, j] < minval) { minval = M[row, j]; imin = j; } } return imin; }
Greedy TSP publicstaticvoid doGreedyTSP(int p) { int k = 0; do { itour[k] = p; tour[k] = L[p]; used[itour[k]] = true; p = minAvail(p); k += 1; } while (k < n); }
Results Starting with each City tour = [ A E C G F D B H ] tour length = 28 tour = [ B H A E C G F D ] tour length = 28 tour = [ C G F E A B H D ] tour length = 34 tour = [ D E A B H C G F ] tour length = 30 tour = [ E A B H C G F D ] tour length = 30 tour = [ F E A B H C G D ] tour length = 37 tour = [ G F E A B H C D ] tour length = 37 tour = [ H A E C G F D B ] tour length = 28