示例#1
0
        internal void AddEdge(Dictionary <CaveNode, Dictionary <CaveNode, int> > graph, CaveNode n1, CaveNode n2, int weight)
        {
            if (graph.ContainsKey(n1) == false)
            {
                graph.Add(n1, new Dictionary <CaveNode, int>());
            }

            if (graph[n1].ContainsKey(n2))
            {
                graph[n1][n2] = weight;
            }
            else
            {
                graph[n1].Add(n2, weight);
            }

            if (graph.ContainsKey(n2) == false)
            {
                graph.Add(n2, new Dictionary <CaveNode, int>());
            }

            if (graph[n2].ContainsKey(n1))
            {
                graph[n2][n1] = weight;
            }
            else
            {
                graph[n2].Add(n1, weight);
            }
        }
示例#2
0
        internal Dictionary <CaveNode, int> dijkstra(Dictionary <CaveNode, Dictionary <CaveNode, int> > graph, CaveNode start)
        {
            Dictionary <CaveNode, int> dist = new Dictionary <CaveNode, int>();
            PriorityQueue <CaveNode>   q2   = new PriorityQueue <CaveNode>();
            HashSet <CaveNode>         seen = new HashSet <CaveNode>();

            dist.Add(start, 0);
            foreach (CaveNode v in graph.Keys)
            {
                if (v.Equals(start) == false)
                {
                    dist.Add(v, int.MaxValue);
                }

                q2.AddOrUpdate(v, dist[v]);
            }

            while (q2.Count != 0)
            {
                /* get the smallest vertex */
                //var abc = q.Min(z => dist[z]);
                //var u = q.Where(z => dist[z] == abc).First();

                //q.Remove(u);
                CaveNode u;
                if (q2.TryDequeueMin(out u) == false)
                {
                    Debugger.Break();
                }

                seen.Add(u);

                foreach (CaveNode v in graph[u].Keys)
                {
                    if (seen.Contains(v))
                    {
                        continue;
                    }

                    var alt = dist[u] + graph[u][v];
                    if (alt < dist[v])
                    {
                        dist[v] = alt;
                        q2.AddOrUpdate(v, dist[v]);
                    }
                }
            }
            return(dist);
        }