예제 #1
0
        /// <summary>
        /// Generic BFS function. Can be used to solve any problem that requires BFS, just plug in the inspectionFunc.
        /// </summary>
        /// <param name="inspectFunc">Must return true if the search is completed and no more nodes need to be checked</param>
        /// <param name="startId">Starting node, by default it is 0.</param>
        public void Bfs(Func <DirectedGraphNode <T>, bool> inspectFunc, bool countComponents)
        {
            List <DirectedGraphNode <T> > nodes = Nodes.Values.ToList();

            if (nodes.Count == 0)
            {
                return;
            }

            bool[] visited = new bool[nodes.Count];
            visited.Initialize();
            Queue <DirectedGraphNode <T> > nodeQueue = new Queue <DirectedGraphNode <T> >();

            foreach (var undirectedGraphNode in nodes)
            {
                int currentNodeId = nodes.IndexOf(undirectedGraphNode);
                if (!visited[currentNodeId])
                {
                    if (countComponents)
                    {
                        NumberOfComponents++;
                    }
                    nodeQueue.Enqueue(undirectedGraphNode);
                    visited[currentNodeId] = true;
                    while (nodeQueue.Count != 0)
                    {
                        DirectedGraphNode <T> currentNode = nodeQueue.Dequeue();

                        if (inspectFunc != null && inspectFunc(currentNode))
                        {
                            return;
                        }

                        foreach (DirectedGraphNode <T> neighbor in currentNode.GetNeighbors())
                        {
                            if (!visited[nodes.IndexOf(neighbor)])
                            {
                                visited[nodes.IndexOf(neighbor)] = true;
                                nodeQueue.Enqueue(neighbor);
                            }
                        }
                    }
                }
            }
        }
예제 #2
0
        private void InternalDfs(List <DirectedGraphNode <T> > nodes, bool[] visited, DirectedGraphNode <T> node, Func <DirectedGraphNode <T>, bool> inspectFunc)
        {
            int nodeId = nodes.IndexOf(node);

            visited[nodeId] = true;
            int childLoopItteration = 0;

            foreach (DirectedGraphNode <T> neighbor in node.GetNeighbors())
            {
                if (inspectFunc(neighbor))
                {
                    return;
                }
                if (!visited[nodes.IndexOf(neighbor)])
                {
                    InternalDfs(nodes, visited, neighbor, inspectFunc);
                }
                childLoopItteration++;
            }
        }