public void Test() { var pq = new IndexMinPQ <int>(10); pq.Enqueue(1, 20); pq.Enqueue(2, 15); Assert.Equal(15, pq.MinKey()); pq.Enqueue(1, 10); Assert.Equal(10, pq.MinKey()); pq.Enqueue(3, 11); Assert.Equal(1, pq.DelMin()); Assert.Equal(11, pq.MinKey()); Assert.Equal(2, pq.Count); Assert.False(pq.IsEmpty); pq.Enqueue(2, 10); Assert.Equal(10, pq.MinKey()); Assert.Equal(2, pq.DelMin()); foreach (var v in pq) { console.WriteLine("key: {0}", v); } }
/// <summary> /// Demo test the <c>IndexMinPQ</c> data type.</summary> /// <param name="args">Place holder for user arguments</param> /// public static void MainTest(string[] args) { // insert a bunch of strings string[] strings = { "it", "was", "the", "best", "of", "times", "it", "was", "the", "worst" }; IndexMinPQ <string> pq = new IndexMinPQ <string>(strings.Length); for (int i = 0; i < strings.Length; i++) { pq.Insert(i, strings[i]); } // delete and print each key while (!pq.IsEmpty) { int i = pq.DelMin(); Console.WriteLine(i + " " + strings[i]); } Console.WriteLine(); // reinsert the same strings for (int i = 0; i < strings.Length; i++) { pq.Insert(i, strings[i]); } // print each key using the iterator foreach (int i in pq) { Console.WriteLine(i + " " + strings[i]); } while (!pq.IsEmpty) { Console.WriteLine("Min k={0} at {1}", pq.MinKey, pq.MinIndex); Console.WriteLine("Removed {0}", pq.DelMin()); } }
public void IndexMinPQTest1() { const int MaxSize = 8; const double MinValue = 3.9; const double MaxValue = MinValue * MaxSize + 32; int index; // MinValue index == 3, MaxValue index == 4 double[] items = { MinValue * 2, MinValue * 3, MinValue * 4, MinValue, MaxValue, MinValue * 5, MinValue * 6, MinValue * 7 }; StdRandom.Seed = 101; IndexMinPQ <double> pq = new IndexMinPQ <double>(MaxSize); index = StdRandom.Uniform(items.Length); Assert.IsFalse(pq.Contains(index)); Assert.IsTrue(pq.IsEmpty); Assert.AreEqual(0, pq.Count); try { index = pq.DelMin(); Assert.Fail("Failed to catch exception"); } catch (InvalidOperationException) { } for (int i = 0; i < items.Length; i++) { pq.Insert(i, items[i]); } Assert.AreEqual(items.Length, pq.Count); Assert.AreEqual(MinValue, pq.MinKey); Assert.AreEqual(3, pq.MinIndex); Assert.AreEqual(MaxValue, pq.KeyOf(4)); index = StdRandom.Uniform(items.Length); Assert.AreEqual(items[index], pq.KeyOf(index)); pq.ChangeKey(1, pq.MinKey * 0.9); // make it the smallest item Assert.AreEqual(1, pq.MinIndex); pq.DecreaseKey(3, pq.MinKey * 0.87); Assert.AreEqual(3, pq.MinIndex); pq.Delete(3); Assert.AreNotEqual(3, pq.MinIndex); Assert.AreEqual(1, pq.DelMin()); }
public Dijkstra(WeightedDiGraph G, int s) { this.s = s; int V = G.V(); marked = new bool[V]; edgeTo = new Edge[V]; cost = new double[V]; for (var i = 0; i < V; ++i) { cost[i] = Double.MaxValue; } cost[s] = 0; pq = new IndexMinPQ <Double>(V); pq.Insert(s, 0); while (!pq.IsEmpty) { var v = pq.DelMin(); marked[v] = true; foreach (var e in G.adj(v)) { Relax(G, e); } } }
private readonly IndexMinPQ <Double> _pq; // priority queue of vertices /// <summary> /// Computes a shortest-paths tree from the source vertex <tt>s</tt> to every other /// vertex in the edge-weighted digraph <tt>G</tt>. /// </summary> /// <param name="g">g the edge-weighted digraph</param> /// <param name="s">s the source vertex</param> /// <exception cref="ArgumentException">if an edge weight is negative</exception> /// <exception cref="ArgumentException">unless 0 <= <tt>s</tt> <= <tt>V</tt> - 1</exception> public DijkstraSP(EdgeWeightedDigraph g, int s) { foreach (var e in g.Edges()) { if (e.Weight < 0) { throw new ArgumentException($"edge {e} has negative weight"); } } _distTo = new double[g.V]; _edgeTo = new DirectedEdge[g.V]; for (var v = 0; v < g.V; v++) { _distTo[v] = double.PositiveInfinity; } _distTo[s] = 0.0; // relax vertices in order of distance from s _pq = new IndexMinPQ <Double>(g.V); _pq.Insert(s, _distTo[s]); while (!_pq.IsEmpty()) { var v = _pq.DelMin(); foreach (var e in g.Adj(v)) { Relax(e); } } // check optimality conditions //assert check(G, s); }
public LazyPrimMinSpanningTree(EdgeWeightedGraph g) { pq = new IndexMinPQ <Edge>(g.EdgeCount); marked = new bool[g.VertexCount]; mst = new Queue <Edge>(); Visit(g, 0); while (!pq.IsEmpty()) { Edge e = pq.DelMin(); int v1 = e.CurrentValue; int v2 = e.Other(v1); if (marked[v1] && marked[v2]) { continue; } mst.Enqueue(e); if (marked[v1]) { Visit(g, v1); } if (!marked[v2]) { Visit(g, v2); } } }
public DijkstraSP(EdgeWeightedDigraph g, int s) { foreach (DirectedEdge e in g.Edges()) { if (e.Weight() < 0) { throw new ArgumentOutOfRangeException("graph edge must have nonegative weights"); } } distTo = new double[g.V]; edgeTo = new DirectedEdge[g.V]; for (int v = 0; v < g.V; v++) { distTo[v] = double.PositiveInfinity; } distTo[s] = 0; //relax vertices in order of distance from s pq = new IndexMinPQ <double>(g.V); pq.Insert(s, distTo[s]); while (!pq.IsEmpty()) { int v = pq.DelMin(); foreach (DirectedEdge e in g.Adj(v)) { relax(e); } } }
private readonly IndexMinPQ<Double> _pq; // priority queue of vertices #endregion Fields #region Constructors /// <summary> /// Computes a shortest-paths tree from the source vertex <tt>s</tt> to every /// other vertex in the edge-weighted graph <tt>G</tt>. /// </summary> /// <param name="g">g the edge-weighted graph</param> /// <param name="s">s the source vertex</param> /// <exception cref="ArgumentException">if an edge weight is negative</exception> /// <exception cref="ArgumentException">unless 0 <= <tt>s</tt> <= <tt>V</tt> - 1</exception> public DijkstraUndirectedSP(EdgeWeightedGraph g, int s) { foreach (var e in g.Edges()) { if (e.Weight < 0) throw new ArgumentException($"edge {e} has negative weight"); } _distTo = new double[g.V]; _edgeTo = new EdgeW[g.V]; for (var v = 0; v < g.V; v++) _distTo[v] = double.PositiveInfinity; _distTo[s] = 0.0; // relax vertices in order of distance from s _pq = new IndexMinPQ<Double>(g.V); _pq.Insert(s, _distTo[s]); while (!_pq.IsEmpty()) { var v = _pq.DelMin(); foreach (var e in g.Adj(v)) Relax(e, v); } // check optimality conditions //assert check(G, s); }
/// <summary> /// run Prim's algorithm in graph G, starting from vertex s /// </summary> /// <param name="g"></param> /// <param name="s"></param> private void Prim(EdgeWeightedGraph g, int s) { _distTo[s] = 0.0; _pq.Insert(s, _distTo[s]); while (!_pq.IsEmpty()) { var v = _pq.DelMin(); Scan(g, v); } }
private void prim(EdgeWeightedGraph g, int s) { distTo[s] = 0.0; pq.Insert(s, distTo[s]); while (!pq.IsEmpty()) { int v = pq.DelMin(); scan(g, v); } }
public DifkstraSP(EdgeWeightedDigraph g, int s) { _edgeTo = new DirectedEdge[g.V]; _distTo = Enumerable.Repeat(double.PositiveInfinity, g.V).ToArray(); _pq = new IndexMinPQ <double>(g.V); _distTo[s] = 0.0; _pq.Insert(s, 0.0); while (!_pq.IsEmpty()) { Relax(g, _pq.DelMin()); } }
public DijkstraAlgorithm(EdgeWeightedDigraph digraph, int source) : base(digraph, source) { //pq maintain a set of vertex need to deal with. IndexMinPQ <double> pq = new IndexMinPQ <double>(digraph.V); pq.Insert(source, distTo[source]); while (!pq.IsEmpty()) { //when v pops up, the distance and path to v have been confirmed int v = pq.DelMin(); foreach (DirectedEdge e in digraph.Adj(v)) { Relax(pq, e); } } }
void IndexMinPQTest() { var strArr = FileHandler.ReadFileAsStrArr("words3.txt"); strArr.Show(); var pq = new IndexMinPQ <string>(strArr.Length); for (int i = 0; i < strArr.Length; i++) { pq.Insert(i, strArr[i]); } while (!pq.IsEmpty()) { Console.WriteLine(pq.DelMin()); } Console.WriteLine(); Console.ReadKey(); }
private readonly decimal[] _distTo; // distTo[v] = distance of shortest s->v path #endregion Fields #region Constructors /** * Computes a shortest paths tree from <tt>s</tt> to every other vertex in * the edge-weighted digraph <tt>G</tt>. * @param G the edge-weighted digraph * @param s the source vertex * @throws IllegalArgumentException if an edge weight is negative * @throws IllegalArgumentException unless 0 ≤ <tt>s</tt> ≤ <tt>V</tt> - 1 */ public ShortestNeuronPath(NeuronGraph G, int s) { _distTo = new decimal[G.V()]; edgeTo = new DirectedEdge[G.V()]; for (int v = 0; v < G.V(); v++) _distTo[v] = decimal.MaxValue; _distTo[s] = 0.0M; // relax vertices in order of distance from s pq = new IndexMinPQ<decimal>(G.V()); pq.Insert(s, _distTo[s]); while (!pq.IsEmpty()) { int v = pq.DelMin(); foreach (DirectedEdge e in G.adj(v)) relax(e); } }
public void IndexMinPQ_Dequeue() { var q = new IndexMinPQ<int>(items.Length); for (int i = 0; i < items.Length; i++) { q.Insert(i, items[i]); } var sortedItems = new List<int>(items); sortedItems.Sort(); foreach (var item in sortedItems) { // The top of the queue returns the items in sorted order var minIndex = q.DelMin(); Assert.AreEqual(items[minIndex], item); } }
public DijkstraSP(EdgeWeightedDigraph graph, int startVertex) { edgeTo = new DirectedEdge[graph.Vertices]; distTo = new double[graph.Vertices]; priorityQueue = new IndexMinPQ <double>(graph.Vertices); for (int v = 0; v < graph.Vertices; v++) { distTo[v] = double.MaxValue; } distTo[startVertex] = 0.0f; priorityQueue.Insert(startVertex, 0.0f); while (!priorityQueue.IsEmpty()) { Relax(graph, priorityQueue.DelMin()); } }
public KruskalMinSpanningTree(EdgeWeightedGraph g) { mst = new Queue <Edge>(); IndexMinPQ <Edge> pq = new IndexMinPQ <Edge>(g.EdgeCount); UnionFind_1 uf = new UnionFind_1(g.VertexCount); while (!pq.IsEmpty() && mst.Count < g.VertexCount - 1) { Edge e = pq.DelMin(); int v1 = e.V1; int v2 = e.Other(v1); if (uf.Connected(v1, v2)) { continue; } uf.Union(v1, v2); mst.Enqueue(e); } }
public void DifkstraSPMy(EdgeWeightedDigraph g, int s) { _edgeTo = new DirectedEdge[g.V]; _distTo = Enumerable.Repeat(double.PositiveInfinity, g.V).ToArray(); _distTo[s] = 0.0; _pq = new IndexMinPQ <double>(g.V); foreach (var e in g.Adj(s)) { _edgeTo[e.To] = e; _distTo[e.To] = e.Weight; _pq.Insert(e.To, e.Weight); } while (!_pq.IsEmpty()) { var i = _pq.DelMin(); foreach (var e in g.Adj(i)) { RelaxMy(i, e); } } }
public DijkstraSP(EdgeWeightedDiagraph g, int source) { vertexNumber = g.V(); distTo = new double[vertexNumber]; for (int i = 0; i < vertexNumber; i++) { distTo[i] = double.PositiveInfinity; } distTo[source] = 0.0; edgeTo = new DirectedEdge[vertexNumber]; pq = new IndexMinPQ <double>(vertexNumber); pq.Insert(source, 0.0); while (!pq.IsEmpty()) { int current = pq.DelMin(); Relax(g, current); } }
public PrimMst(EdgeWeightedGraph graph) { edgeTo = new Edge[graph.Vertices]; distTo = new double[graph.Vertices]; marked = new bool[graph.Vertices]; for (int vertex = 0; vertex < graph.Vertices; vertex++) { distTo[vertex] = double.MaxValue; } prioryQueue = new IndexMinPQ <double>(graph.Vertices); distTo[0] = 0.0f; prioryQueue.Insert(0, 0.0f); while (!prioryQueue.IsEmpty()) { Visit(graph, prioryQueue.DelMin()); } }
//ctor inits DSs, builds shortest path tree and computes distances //takes a built DiGraph and a source vertex public DijkstrasShortestPath(EdgeWeightedDiGraph g, int s) { _pq = new IndexMinPQ <double>(g.V); _edgeTo = new DirectedEdge[g.V]; _distTo = new double[g.V]; //load initial values for (int i = 1; i < g.V; i++) { _distTo[i] = Double.PositiveInfinity; } _distTo[s] = 0.0; _edgeTo[s] = null; //loads a starting value onto PQ to start process _pq.Insert(s, _distTo[s]); //start business logic //start cycle of deleting min edges and checking adj edges for 'eligability' while (!_pq.IsEmpty()) { var minV = _pq.DelMin(); Relax(g, minV); } }
public EagerPrim(WeightedGraph G) { int V = G.V(); pq = new IndexMinPQ <Edge>(V); marked = new bool[V]; Visit(G, 0); path = new List <Edge>(); while (!pq.IsEmpty) { var e = pq.MinKey(); var v = pq.DelMin(); path.Add(e); if (!marked[v]) { Visit(G, v); } } }
// Returns shortest path from src to dst (not including src) public List <TileNode> GetShortestPath(Vector2Int src, Vector2Int dst, UnitType unitType) { float[,] distance = new float[width, height]; Vector2Int[,] prev = new Vector2Int[width, height]; IndexMinPQ <float> minPQ = new IndexMinPQ <float>(width * height); distance[src.x, src.y] = 0.0f; prev[src.x, src.y] = src; minPQ.Insert(ToTileIndex1D(src), 0.0f); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (i == src.x && j == src.y) { continue; } distance[i, j] = float.PositiveInfinity; prev[i, j] = new Vector2Int(-1, -1); minPQ.Insert(ToTileIndex1D(i, j), float.PositiveInfinity); } } while (!minPQ.IsEmpty) { float dist = minPQ.MinKey; Vector2Int min = ToTileIndex2D(minPQ.DelMin()); Vector2Int[] neighbors = GetNeighbors(min); foreach (Vector2Int neighbor in neighbors) { int neighborInd = ToTileIndex1D(neighbor); float edgeDist = GetTileMoveWeight(neighbor, unitType); if (minPQ.Contains(neighborInd) && edgeDist != 0.0f) { float currentDist = minPQ.KeyOf(neighborInd); if (dist + edgeDist < currentDist) { distance[neighbor.x, neighbor.y] = dist + edgeDist; prev[neighbor.x, neighbor.y] = min; minPQ.DecreaseKey(neighborInd, dist + edgeDist); } } } } if (distance[dst.x, dst.y] == float.PositiveInfinity) { return(null); } List <TileNode> path = new List <TileNode>(); TileNode dstNode; dstNode.coords = dst; dstNode.dist = distance[dst.x, dst.y]; path.Add(dstNode); Vector2Int tile = dst; while (prev[tile.x, tile.y] != src) { tile = prev[tile.x, tile.y]; TileNode node; node.coords = tile; node.dist = distance[tile.x, tile.y]; path.Add(node); } path.Reverse(); return(path); }