Implementing Depth First Search into C# using List and Stack

前端 未结 6 1067
甜味超标
甜味超标 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:37

    You might enjoy this:

            public static bool DepthFirstSearch(this IEnumerable vertices, T rootVertex, T targetVertex, Func> getConnectedVertices, Func matchFunction = null)
        {
            if (getConnectedVertices == null)
            {
                throw new ArgumentNullException("getConnectedVertices");
            }
            if (matchFunction == null)
            {
                matchFunction = (t, u) => object.Equals(t, u);
            }
            var directlyConnectedVertices = getConnectedVertices(rootVertex);
            foreach (var vertex in directlyConnectedVertices)
            {
                if (matchFunction(vertex, targetVertex))
                {
                    return true;
                }
                else if (vertices.DepthFirstSearch(vertex, targetVertex, getConnectedVertices, matchFunction))
                {
                    return true;
                }
            }
            return false;
        }
    

提交回复
热议问题