/// <summary> /// 获得最短路径。 /// </summary> /// <param name="start">起始状态。</param> /// <param name="goal">终止状态。</param> /// <returns></returns> public T[] GetPath(T start, T goal) { Dictionary <T, T> comeFrom = new Dictionary <T, T>(this.equalityComparer); Dictionary <T, int> gScore = new Dictionary <T, int>(this.equalityComparer); Dictionary <T, int> fScore = new Dictionary <T, int>(this.equalityComparer); MinPQ <T> openSet = new MinPQ <T>(new FScoreComparer(fScore), this.equalityComparer); HashSet <T> closeSet = new HashSet <T>(this.equalityComparer); openSet.Insert(start); gScore.Add(start, 0); fScore.Add(start, HeuristicDistance(start, goal)); while (!openSet.IsEmpty()) { T current = openSet.DelMin(); if (this.equalityComparer.Equals(current, goal)) { return(ReconstructPath(comeFrom, current)); } closeSet.Add(current); T[] neighbors = GetNeighbors(current); foreach (T neighbor in neighbors) { if (closeSet.Contains(neighbor)) { continue; } int gScoreTentative = gScore[current] + ActualDistance(current, neighbor); // 新状态 if (!openSet.Contains(neighbor)) { openSet.Insert(neighbor); } else if (gScoreTentative >= gScore[neighbor]) { continue; } // 记录新状态 comeFrom[neighbor] = current; gScore[neighbor] = gScoreTentative; fScore[neighbor] = gScore[neighbor] + HeuristicDistance(neighbor, goal); } } return(null); }
/// <summary> /// 获取堆的迭代器,元素以升序排列。 /// </summary> /// <returns></returns> public IEnumerator <Key> GetEnumerator() { MinPQ <Key> copy = new MinPQ <Key>(this.n); for (int i = 1; i <= this.n; i++) { copy.Insert(this.pq[i]); } while (!copy.IsEmpty()) { yield return(copy.DelMin()); // 下次迭代的时候从这里继续执行。 } }
/// <summary> /// 获取堆的迭代器,元素以升序排列。 /// </summary> /// <returns>最小堆的迭代器。</returns> public IEnumerator <Key> GetEnumerator() { var copy = new MinPQ <Key>(n); for (var i = 1; i <= n; i++) { copy.Insert(pq[i]); } while (!copy.IsEmpty()) { yield return(copy.DelMin()); // 下次迭代的时候从这里继续执行。 } }