public static IEnumerable <int> BreathFirstSearch(IEnumerable <int> starts, AdjacencyListGraph <long> graph)
        {
            var visited = new SearchData <bool>(graph.Size(), false);
            var queue   = new Queue <int>();

            foreach (var start in starts)
            {
                visited.SetValue(start, false);
                queue.Enqueue(start);
            }

            while (queue.Any())
            {
                var current = queue.Dequeue();
                foreach (var neighbor in graph.NeighborIndexes(current).Where(i => i != current))
                {
                    if (visited.Visited(neighbor))
                    {
                        continue;
                    }

                    queue.Enqueue(neighbor);
                    visited.SetValue(neighbor, true);
                }
            }

            var visitedIndexes = visited.Values
                                 .Select((v, i) => new { Visited = v, Index = i })
                                 .Where(x => x.Visited)
                                 .Select(x => x.Index);

            return(visitedIndexes);
        }
Esempio n. 2
0
        private void Explore(int start)
        {
            _visitedFrom = new SearchData <int>(_graph.Size(), -1);
            _distance    = new SearchData <int>(_graph.Size(), MaxDistance);
            _distance.SetValue(start, 0);

            //Make Prioirty Queue
            var pq = new MinPriorityQueue <long>(_graph.Size(), long.MaxValue);

            for (var i = 0; i < _distance.Length; i++)
            {
                pq.Enqueue(i, _distance.GetValue(i));
            }

            while (!pq.IsEmpty())
            {
                //Console.WriteLine("Queue: {0}", pq);

                var currentIndex = pq.Dequeue();

                //Console.WriteLine("Extract: {0}", currentIndex);

                foreach (var edge in _graph.Neighbors(currentIndex))
                {
                    var neighborIndex = edge.Right;
                    var d             = _distance.GetValue(neighborIndex);
                    var dFromC        = _distance.GetValue(currentIndex) == MaxDistance
                        ? MaxDistance
                        : _distance.GetValue(currentIndex) + (int)edge.Weight;

                    //Console.WriteLine("Edge {1} => {0} : Distance {2} : {3}",neighborIndex,currentIndex,dFromC,d);

                    if (d <= dFromC)
                    {
                        continue;
                    }

                    //Set New Distance Values
                    _distance.SetValue(neighborIndex, dFromC);
                    _visitedFrom.SetValue(neighborIndex, currentIndex);
                    pq.ChangePriority(neighborIndex, dFromC);
                }
            }
        }