Ejemplo n.º 1
0
        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);
        }
Ejemplo n.º 2
0
        private AdjacencyListGraph ToAdjacencyGraph(Action <AdjacencyListGraph, Edge> addEdge)
        {
            var line0        = ParseIntPair(_inputs[0]);
            var verticeCount = line0.Item1;
            var edgeCount    = line0.Item2;
            var graph        = new AdjacencyListGraph(verticeCount);

            foreach (var edge in Enumerable.Range(1, edgeCount).Select(i => ParseEdge(_inputs[i])))
            {
                addEdge(graph, edge);
            }
            _lineCursor = edgeCount + 1;

            return(graph);
        }
Ejemplo n.º 3
0
        private static BellmanFordResult ShortestPath(int start, int size, List <Edge <long> > edges)
        {
            var g = new AdjacencyListGraph <long>(size);

            foreach (var edge in edges)
            {
                g.AddDirectedEdge(edge);
            }

            var result   = BellmanFord(start, size, edges);
            var negative = edges
                           .Where(e => ShouldRelax(e.Left, e.Right, e.Weight, result).Item1)
                           .Select(e => e.Right)
                           .ToList();

            foreach (var i in BreathFirstSearch(negative, g))
            {
                result.Distance.SetValue(i, NegativeInfinity);
            }
            return(result);
        }
Ejemplo n.º 4
0
 public Dijkstras(AdjacencyListGraph <long> g)
 {
     _graph = g;
 }
Ejemplo n.º 5
0
 public DijkstrasAlgorithm(AdjacencyListGraph g)
 {
     _graph = g;
 }