using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static List<(string lujin, int length)> GroupLuXian = new List<(string lujin, int length)>(); static List<List<(char dian, int length)>> luxian = new List<List<(char dian, int length)>>(); static void Main(string[] args) { //使用数组保存这些点之间的关系 按A-E排序 luxian.Add(new List<(char dian, int length)> { (‘B‘,6),(‘C‘,8) });//a luxian.Add(new List<(char dian, int length)> { (‘A‘,6),(‘D‘,3),(‘E‘,4) });//b luxian.Add(new List<(char dian, int length)> { (‘A‘,8),(‘F‘,4),(‘D‘,4) });//c luxian.Add(new List<(char dian, int length)> { (‘B‘,3),(‘C‘,4),(‘E‘,5) });//d luxian.Add(new List<(char dian, int length)> { (‘B‘,4),(‘G‘,7),(‘D‘,5) });//e luxian.Add(new List<(char dian, int length)> { (‘D‘,4),(‘G‘,4),(‘C‘,4) });//f luxian.Add(new List<(char dian, int length)> { (‘F‘,4),(‘E‘,7) });//g //数据构建完成 开始计算 Stopwatch watch = new Stopwatch(); watch.Start(); GetLength(luxian[0], 0, "A"); watch.Stop(); Console.WriteLine("最短路长度为:"+GroupLuXian.OrderBy(u=>u.length).First().length+"消耗时间:"+watch.Elapsed); foreach (var item in GroupLuXian) { Console.WriteLine(item.lujin+"长度"+item.length); } Console.Read(); } public static int GetIndex(char c) { switch (c) { case ‘A‘: return 0; case ‘B‘: return 1; case ‘C‘: return 2; case ‘D‘: return 3; case ‘E‘: return 4; case ‘F‘: return 5; case ‘G‘: return 6; } return -1; } public static void GetLength(List<(char dian, int length)> dian, int length, string lujin) { if (dian == null || dian.Count == 0) return; for (int i = 0; i < dian.Count; i++) { //判断是否包含终点 if (lujin.Contains(dian[i].dian)) continue; if (dian[i].dian == ‘G‘) GroupLuXian.Add((lujin + ‘G‘, length + dian[i].length)); else GetLength(luxian[GetIndex(dian[i].dian)], length + dian[i].length, lujin + dian[i].dian); } } } }
时间: 2024-11-06 07:23:09