Implementing Depth First Search into C# using List and Stack

前端 未结 6 1031
甜味超标
甜味超标 2020-12-07 16:43

I want to create a depth first search which I have been somewhat successful in.

Here is my code so far (Except my constructor, note the Vertex and Edge classes only

6条回答
  •  失恋的感觉
    2020-12-07 17:35

    This is my implemenation, one stack is good enough. A reverse is done before the foreach loop.

        /// 
        /// Depth first search implementation in c#
        /// 
        /// Type of tree structure item
        /// Type of childs collection
        /// Starting node to search
        /// Property to return child node
        /// Predicate for matching
        /// The instance of matched result, null if not found
        public static T DepthFirstSearch(this T node, Func ChildsProperty, Predicate Match) 
            where T:class
        {
            if (!(ChildsProperty(node) is IEnumerable))
                throw new ArgumentException("ChildsProperty must be IEnumerable");
    
            Stack stack = new Stack();
            stack.Push(node);
            while (stack.Count > 0) {
                T thisNode = stack.Pop();
                #if DEBUG
                System.Diagnostics.Debug.WriteLine(thisNode.ToString());
                #endif
                if (Match(thisNode))
                    return thisNode;
                if (ChildsProperty(thisNode) != null) {
                    foreach (T child in (ChildsProperty(thisNode) as IEnumerable).Reverse()) 
                        stack.Push(child);
                }
            }
            return null;
        }
    

提交回复
热议问题