Beispiel #1
0
        public IPath BuildPath(string from)
        {
            _path = new Path(from);
            var start = _graph.GetVertex(from);

            var queue = new Queue <IVertex>();

            queue.Enqueue(start);
            while (queue.Count > 0)
            {
                var current = queue.Dequeue();
                var edges   = current.GetEdges().ToArray();
                _visited.Add(current.Name);
                if (edges.Length == 0)
                {
                    continue;
                }

                foreach (var edge in edges)
                {
                    if (!_visited.Contains(edge.Vertex2.Name))
                    {
                        queue.Enqueue(edge.Vertex2);
                        _path.Set(edge.Vertex2.Name, current.Name);
                    }
                }
            }

            return(_path);
        }
Beispiel #2
0
        public IPath BuildPath(string from)
        {
            _path = new Path(from);
            var start = _graph.GetVertex(from);

            _costs.Add(start.Name, 0);
            var current = start;

            while (current != null)
            {
                var edges = current.GetEdges().OrderBy(x => x.Weight).ToArray();
                foreach (var edge in edges)
                {
                    if (_visited.Contains(edge.Vertex2.Name))
                    {
                        continue;
                    }

                    if (!_costs.TryGetValue(edge.Vertex2.Name, out var cost) || cost > edge.Weight + _costs[current.Name])
                    {
                        _costs[edge.Vertex2.Name] = edge.Weight + _costs[current.Name];
                        _path.Set(edge.Vertex2.Name, current.Name);
                    }
                }

                _visited.Add(current.Name);

                current = edges.Where(e => !_visited.Contains(e.Vertex2.Name))
                          .OrderBy(e => _costs.TryGetValue(e.Vertex2.Name, out var cost) ? cost : int.MaxValue)
                          .FirstOrDefault()?.Vertex2;
            }

            return(_path);
        }
Beispiel #3
0
        public IPath BuildPath(string from)
        {
            _path = new Path(from);
            var start = _graph.GetVertex(from);

            DfsSearch(start);

            return(_path);
        }