码迷,mamicode.com
首页 > Windows程序 > 详细

C# - 广度优先搜索

时间:2020-07-04 18:46:19      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:nbsp   rap   private   col   sum   说明   完整   new   没有   

    public class Route<T>
    {
        /// <summary>
        /// 终点相对于起点的维度
        /// </summary>
        public int Dimension { get; }

        /// <summary>
        /// 完整路线
        /// </summary>
        public string FullRoute { get; }

        public Route(Stack<T> stack)
        {
            FullRoute = string.Join(",", stack);
            Dimension = stack.Count - 1;
        }
    }

 

    public class RouteNode<T>
    {
        public T Value { get; }
        public RouteNode<T> Parent { get; set; }

        public RouteNode(T value)
        {
            Value = value;
        }

        public Route<T> Route
        {
            get
            {
                var stack = new Stack<T>();
                stack.Push(this.Value);
                var parent = Parent;
                while (parent != null)
                {
                    stack.Push(parent.Value);
                    parent = parent.Parent;
                }
                Route<T> route = new Route<T>(stack);
                return route;
            }
        }
    }

 

    public class MyGraph<T> where T : IComparable<T>
    {
        //节点集合
        private readonly Dictionary<T, IList<T>> _nodes;

        public MyGraph() : this(new Dictionary<T, IList<T>>())
        {

        }

        public MyGraph(Dictionary<T, IList<T>> nodes)
        {
            _nodes = nodes;
        }

        public void Add(T key, IList<T> value)
        {
            _nodes.Add(key, value);
        }

        /// <summary>
        /// 判断是否有从 start 到 end 的路径
        /// </summary>
        /// <param name="start">开始点</param>
        /// <param name="end">结束点</param>
        /// <param name="route">路线</param>
        /// <returns></returns>
        public bool TryFindMinRoute(T start, T end, out Route<T> route)
        {
            route = null;
            if (_nodes.TryGetValue(start, out var nodes) == false)
            {
                throw new Exception("not find the element:" + start);
            }
            if (nodes == null || nodes.Count == 0)
            {
                return false;
            }
            //已搜索元素的集合
            var searched = new HashSet<T>();
            //将要搜索的节点队列
            var searching = new Queue<RouteNode<T>>();
            foreach (var item in nodes)
            {
                searching.Enqueue(new RouteNode<T>(item)
                {
                    Parent = new RouteNode<T>(start),
                });
            }

            while (searching.Count > 0)
            {
                RouteNode<T> node = searching.Dequeue();

                //判断当前元素是否搜索过,避免无限循环.
                if (searched.Contains(node.Value))
                {
                    continue;
                }

                if (node.Value.CompareTo(end) == 0)
                {
                    route = node.Route;
                    return true;
                }

                searched.Add(node.Value);

                if (_nodes.TryGetValue(node.Value, out var forwardNodes) == false || forwardNodes == null || forwardNodes.Count == 0)
                {
                    //说明 当前元素 没有指向任何元素
                    continue;
                }

                foreach (var item in forwardNodes.Where(item => searched.Contains(item) == false))
                {
                    searching.Enqueue(new RouteNode<T>(item)
                    {
                        Parent = node
                    });
                }
            }
            return false;
        }
    }

 

Test:

            MyGraph<string> dic = new MyGraph<string>();
            dic.Add("start", new List<string> { "bob", "alice", "claire" });
            dic.Add("bob", new List<string> { "anuj", "dandan1" });
            dic.Add("alice", new List<string> { "peggy" });
            dic.Add("claire", new List<string> { "thom", "jonny" });
            dic.Add("anuj", new List<string>() { "wahaha", "dandan2" });
            dic.Add("dandan2", new List<string>() { "wahaha", "claire" });
            dic.Add("peggy", new List<string>() { "gongwei" });
            dic.Add("gongwei", new List<string>() { "jonny" });
            dic.Add("thom", new List<string>());
            dic.Add("jonny", new List<string> { "refuge" });
            dic.Add("wjire", new List<string>());
            dic.Add("refuge", new List<string>() { "dandan", "bob" });
            var r = dic.TryFindMinRoute("alice", "claire", out var route);
            if (r)
            {
                Console.WriteLine($"在第{route.Dimension}层找到:" + route.FullRoute);
            }
            else
            {
                Console.WriteLine(r);
            }

 

C# - 广度优先搜索

标签:nbsp   rap   private   col   sum   说明   完整   new   没有   

原文地址:https://www.cnblogs.com/refuge/p/13236025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!