Пример #1
0
        /// <summary>
        /// based on the pseudocode on wiki page(http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)
        /// </summary>
        static int using_Dijkstra_s_algorithm_with_priority_queue()
        {
            var len = 80;
            var node_map = new Node[len, len];
            var queue = new PriorityQueue(len * len);
            Node source = null;
            Node goal = null;
            var row = 0;
            var col = 0;
            foreach (var line in File.ReadAllLines("matrix.txt"))
            {
                col = 0;
                foreach (var num in line.Split(new char[] { ',' }))
                {
                    var node = new Node(Convert.ToInt32(num)) { row = row, col = col };
                    if (row == 0 && col == 0) source = node;
                    if (row == len - 1 && col == len - 1) goal = node;
                    // node map is mainly used to get neighbors
                    node_map[row, col] = node;
                    queue.Enqueue(node);
                    col++;
                }
                row++;
            }
            // set the source's distance to zero to kick start the process
            queue.Update(source, 0);
            // code for getting neighbor, using closure with the neighbor_list to make life a little easier
            var neighbor_list = new Node[4]; // 0:left 1:up 2:right 3:down
            Action<Node> prepare_neighbor_list = n =>
                {
                    neighbor_list[0] = n.col - 1 < 0 ? null : node_map[n.row, n.col - 1];
                    neighbor_list[1] = n.row - 1 < 0 ? null : node_map[n.row - 1, n.col];
                    neighbor_list[2] = n.col + 1 >= len ? null : node_map[n.row, n.col + 1];
                    neighbor_list[3] = n.row + 1 >= len ? null : node_map[n.row + 1, n.col];
                };
            var total = 0;
            while (queue.IsEmpty() == false)
            {
                var u = queue.DequeueMin();
                if (u.distance == int.MaxValue)
                    break; // all remaining vertices are inaccessible from source
                if (u == goal)
                {
                    while (u != null)
                    {
                        total += u.cost;
                        u = u.previous;
                    }
                    break;
                }
                // call this method before using neighbor_list array
                prepare_neighbor_list(u);
                foreach (var v in neighbor_list)
                {
                    if (v == null)
                        continue; // like when u is edge cell in the matrix

                    var alt = u.distance + u.cost + v.cost;
                    if (alt < v.distance)
                    {
                        v.previous = u;
                        queue.Update(v, alt);
                    }
                }
            }
            return total;
        }
Пример #2
0
        static void PriorityQueueTest()
        {
            { 
                PriorityQueue<int> queueRemoveMin = new PriorityQueue<int>();
                PriorityQueue<int> queueRemoveMax = new PriorityQueue<int>();
                List<int> doubleCheckMin = new List<int>();
                List<int> doubleCheckMax = new List<int>();
                Random r = new Random();
                // Generate the list of numbers to populate the queue and to check against
                for (int i = 0; i < 20; i++)
                {
                    int randInt = r.Next(-100, 100);
                    doubleCheckMin.Add(randInt);
                }

                for (int i = 0; i < doubleCheckMin.Count; i++)
                {
                    int randInt = doubleCheckMin[i];
                    // heap.Add("" + i, i);
                    queueRemoveMin.Enqueue(randInt, randInt);
                    queueRemoveMax.Enqueue(randInt, randInt);
                    doubleCheckMax.Add(randInt);
                }
                doubleCheckMin.Sort(); // Default. Ascending
                doubleCheckMax.Sort(delegate (int x, int y)
                {
                    if (x == y) return 0;
                    if (x > y) return -1;
                    if (x < y) return 1;
                    return 0;
                });

                Console.WriteLine(" -- NOW REMOVE MIN --");

                int checkCount = 0;
                while (queueRemoveMin.Count > 0)
                {
                    int min = queueRemoveMin.DequeueMin();
                    if (doubleCheckMin[checkCount] != min)
                    {
                        throw new Exception("WRONG!");
                    }
                    checkCount++;
                    Console.WriteLine(min);
                }
                Console.WriteLine(" -- NOW REMOVE MAX --");
                checkCount = 0;
                while (queueRemoveMax.Count > 0)
                {
                    int max = queueRemoveMax.DequeueMax();
                    if (doubleCheckMax[checkCount] != max)
                    {
                        throw new Exception("WRONG!");
                    }
                    checkCount++;
                    Console.WriteLine(max);
                }
            }


            // Now for some random fun. Randomly decide what operation we're performing. 
            // Sorted list is kept alongside for double-checking validity of heap results.
            {
                PriorityQueue<int> queue = new PriorityQueue<int>();
                queue.DebugValidation = true;
                List<int> list = new List<int>();

                const int kMaxOperations = 2000;
                int numOps = 0;
                Random r = new Random();
                for (numOps = 0; numOps < kMaxOperations; numOps++)
                {
                    int randInt = r.Next(0, 4);
                    switch (randInt)
                    {
                        case 0:
                        case 1: // twice as likely to occur
                            {
                                // Add an item.
                                randInt = r.Next(-1000, 1000);
                                Console.WriteLine("Adding : " + randInt);
                                list.Add(randInt);
                                queue.Enqueue(randInt, randInt);
                                if (list.Count != queue.Count)
                                {
                                    throw new Exception("Count mismatch!");
                                }
                            }
                            break;
                        case 2:
                            {
                                // Dequeue Min
                                list.Sort();
                                if (list.Count != queue.Count)
                                {
                                    throw new Exception("Count mismatch! List= " + list.Count + ", queue = " + queue.Count);
                                }
                                if (list.Count == 0)
                                {
                                    // well, can't do much here. early break
                                    break;
                                }
                                int listMin = list[0];
                                list.RemoveAt(0);
                                int queueMin = queue.DequeueMin();
                                if (listMin != queueMin)
                                {
                                    throw new Exception("Min mismatch! List=" + listMin + ", queue=" + queueMin);
                                }
                                Console.WriteLine("DequeueMin : " + queueMin);
                            }

                            break;
                        case 3:
                            {
                                // DequeueMax
                                list.Sort(delegate (int x, int y)
                                {
                                    if (x == y) return 0;
                                    if (x > y) return -1;
                                    if (x < y) return 1;
                                    return 0;
                                });
                                if (list.Count != queue.Count)
                                {
                                    throw new Exception("Count mismatch! List= " + list.Count + ", queue = " + queue.Count);
                                }
                                if (list.Count == 0)
                                {
                                    // well, can't do much here. early break
                                    break;
                                }
                                int listMax = list[0];
                                list.RemoveAt(0);
                                int queueMax = queue.DequeueMax();
                                if (listMax != queueMax)
                                {
                                    throw new Exception("Max mismatch! List=" + listMax + ", queue=" + queueMax);
                                }
                                Console.WriteLine("DequeueMax : " + queueMax);
                            }
                            break;
                    }
                }
                Console.WriteLine("All tests passed!");

            }

        }