c# 无向连通算法(代码极简)

因为游戏寻路需求,要做一个自动跳转地图的功能,为此做了这个无向连通算法,如下图,数字表示地图,比如我要从地图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,是为了往下寻找地图时,不改变之前节点路径,每次回到循环里,都是之前走过的路径。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值