using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Tspform { public class Greedy : Algorithm { static int N = 100; //City Count Tsp tspsolver; private double[] x;// x coordinator of city private double[] y;// y coordinator of city private double[,] dij;//distance of cities private double[] Tk;//store the city which has visited private int[] route;//the route of visited private int[] bestL;// the shortest route private double bestSolution = 100000000000000000; public Greedy(int i, double[] x, double[] y,int startcityNumber,ref int[] bestL, Tsp tspsolver)//initialize the parameter { N = i; this.x = x; this.y = y; this.tspsolver = tspsolver; this.dij = new double[N, N]; this.Tk = new double[N]; this.route = new int[N]; this.bestL = new int[N]; this.bestL = bestL; } public override void ResultRoute()//the salesman start calculate and move { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { dij[i, j] = (new Wj()).Getdistance(x[i], y[i], x[j], y[j]); } } for (int j = 0; j < N; j++) { route[j] = 0; Tk[j] = 0; bestL[j] = 0; } route[0] = Wj.startcityNumber + 2; Tk[route[0]] = 1; //store cities which has visited int s = 1; double dijm = double.MaxValue; int curmin = route[0]; while (s < N) { dijm = double.MaxValue; for (int i = 0; i < N; i++) { if (Tk[i] == 0 && dij[route[s - 1], i] < dijm) { dijm = dij[route[s - 1], i]; curmin = i; } } Tk[curmin] = 1; route[s] = curmin; tspsolver.ShowLength(s, 0); s++; } bestSolution = AllRoute(0); tspsolver.ShowLength(s, bestSolution); tspsolver.DrawRoute(route); } public override double AllRoute(int j)//calculate the final route of the ant ,parameter j is useless,default is zero { double distance = 0; for (int i = 0; i < N - 1; i++) { distance = distance + this.dij[route[i], this.route[i + 1]]; } distance=distance+ dij[route[N - 1], this.route[0]]; return distance; } } }