因为游戏寻路需求,要做一个自动跳转地图的功能,为此做了这个无向连通算法,如下图,数字表示地图,比如我要从地图1走到地图6,有多少种走法,最短路径是哪个。
直接上代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
private static Dictionary<int, int[]> path;
private static List<int> hasPassRoute = new List<int>();
private static int startpos = 1;
private static int endpos = 6;
static void Main(string[] args)
{
path = new Dictionary<int, int[]>();
path.Add(1, new int[] { 2, 3 });
path.Add(2, new int[] { 1, 4,5 });
path.Add(3, new int[] { 1,4,7 });
path.Add(4, new int[] { 2, 3 ,5,8});
path.Add(5, new int[] { 2, 4, 6,8 });
path.Add(6, new int[] { 5,8 });
path.Add(7, new int[] { 3 });
path.Add(8, new int[] { 4,5,6 });
hasPassRoute = new List<int>();
getNextRoute(new List<int>(),startpos);
Console.WriteLine("123");
Console.ReadLine();
}
static void getNextRoute(List<int> routes, int routenum)
{
if (routes.IndexOf(routenum) < 0)
{
routes.Add(routenum);
if (routenum == endpos)
{
for(int i=0;i < routes.Count;i++)
{
Console.Write(routes[i] + "-");
}
Console.WriteLine("");
}
if (path[routenum] != null)
{
int[] neibs = path[routenum];
for (int i = 0; i < neibs.Length; i++)
{
List<int> temproute = new List<int>();
for (int j = 0; j < routes.Count; j++)
temproute.Add(routes[j]);
getNextRoute(temproute, neibs[i]);
}
}
}
}
}
}
以上代码只是找出了所有路径,并没有找出最短的路径,其实很简单,所有路径保存起来,取长度最小的就是了,关键的地方在于 temproute 为什么要在循环里不停的new 一个新的List,是为了往下寻找地图时,不改变之前节点路径,每次回到循环里,都是之前走过的路径。