Exemple #1
0
        public HashSet <T> BreadthFirstSearch <T>(Graph <T> graph, T initialVertex)
        {
            var visited = new HashSet <T>();

            if (!graph.AdjacencyList.ContainsKey(initialVertex))
            {
                return(visited);
            }

            var queue = new SortLib.Collections.Queue <T>(graph.AdjacencyList.Count);

            queue.Enqueue(initialVertex);

            while (queue.Count > 0)
            {
                var vertex = queue.Dequeue();
                if (visited.Contains(vertex))
                {
                    continue;
                }

                visited.Add(vertex);

                foreach (var neighbor in graph.AdjacencyList[vertex])
                {
                    if (!visited.Contains(neighbor))
                    {
                        queue.Enqueue(neighbor);
                    }
                }
            }
            return(visited);
        }
Exemple #2
0
        public Func <T, IEnumerable <T> > ShortestPath <T>(Graph <T> graph, T initialVertex)
        {
            var previous = new Dictionary <T, T>();

            var queue = new SortLib.Collections.Queue <T>(graph.AdjacencyList.Count);

            queue.Enqueue(initialVertex);

            while (queue.Count > 0)
            {
                var vertex = queue.Dequeue();
                foreach (var neighbor in graph.AdjacencyList[vertex])
                {
                    if (previous.ContainsKey(neighbor))
                    {
                        continue;
                    }

                    previous[neighbor] = vertex;
                    queue.Enqueue(neighbor);
                }
            }

            Func <T, IEnumerable <T> > shortestPath = v => {
                var path    = new List <T> {
                };
                var current = v;
                while (!current.Equals(initialVertex))
                {
                    path.Add(current);
                    current = previous[current];
                }
                path.Add(initialVertex);
                path.Reverse();
                return(path);
            };

            return(shortestPath);
        }