Do you know how to implement a priority queue with one key? If so, using two keys doesn't change anything as you just use the dictionary ordering on the keys. That is, implement a priority queue with keys being pairs of integers (x1, y1)
. You say that (x2, y2)
is less than (x1, y1)
if x2 < x1
or if x1 = x2
and y2 < y1
. Now you can just use your previous knowledge of priority queues to solve this problem. You could do this, for example, using a SortedList
with a custom IComparer
.
class Pair<T> {
public T First { get; private set; }
public T Second { get; private set; }
public Pair(T first, T second) {
First = first;
Second = second;
}
public override int GetHashCode() {
return First.GetHashCode() ^ Second.GetHashCode();
}
public override bool Equals(object other) {
Pair<T> pair = other as Pair<T>;
if(pair == null) {
return false;
}
return (this.First.Equals(pair.First) && this.Second.Equals(pair.Second));
}
}
class PairComparer<T> : IComparer<Pair<T>> {
public int Compare(Pair<T> x, Pair<T> y) {
if (x.First.CompareTo(y.First) < 0) {
return -1;
}
else if (x.First.CompareTo(y.First) > 0) {
return 1;
}
else {
return x.Second.CompareTo(y.Second);
}
}
}
Then:
SortedList<Pair<int>, MyClass> list = new SortedList<Pair<int>, MyClass>(new PairComparer<int>());
So that, for example,
SortedList<Pair<int>, string> list = new SortedList<Pair<int>, string>(new PairComparer<int>());
list.Add(new Pair<int>(-1, 1), "l1");
list.Add(new Pair<int>(-2, 1), "e");
list.Add(new Pair<int>(-7, 1), "h");
list.Add(new Pair<int>(-1, 3), "l2");
list.Add(new Pair<int>(0, 5), "o");
foreach (var value in list) {
Console.WriteLine(value.Value);
}
will output
h
e
l1
l2
o
as expected and
foreach(var value in list.Reverse()) {
Console.WriteLine(value.Value);
}
will output
o
l2
l1
e
h
showing that we can iterate from the end too.