BinaryNodeHeap.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver.gameserver.pathfinding.utils;
  16. import com.l2jserver.gameserver.pathfinding.geonodes.GeoNode;
  17. /**
  18. *
  19. * @author -Nemesiss-
  20. */
  21. public class BinaryNodeHeap
  22. {
  23. private final GeoNode[] _list;
  24. private int _size;
  25. public BinaryNodeHeap(int size)
  26. {
  27. _list = new GeoNode[size+1];
  28. _size = 0;
  29. }
  30. public void add(GeoNode n) {
  31. _size++;
  32. int pos = _size;
  33. _list[pos] = n;
  34. while (pos != 1)
  35. {
  36. int p2 = pos/2;
  37. if (_list[pos].getCost() <= _list[p2].getCost())
  38. {
  39. GeoNode temp = _list[p2];
  40. _list[p2] = _list[pos];
  41. _list[pos] = temp;
  42. pos = p2;
  43. }
  44. else
  45. break;
  46. }
  47. }
  48. public GeoNode removeFirst()
  49. {
  50. GeoNode first = _list[1];
  51. _list[1] = _list[_size];
  52. _list[_size] = null;
  53. _size--;
  54. int pos = 1;
  55. int cpos;
  56. int dblcpos;
  57. GeoNode temp;
  58. while(true)
  59. {
  60. cpos = pos;
  61. dblcpos = cpos*2;
  62. if ((dblcpos+1) <= _size)
  63. {
  64. if (_list[cpos].getCost() >= _list[dblcpos].getCost())
  65. pos = dblcpos;
  66. if (_list[pos].getCost() >= _list[dblcpos+1].getCost())
  67. pos = dblcpos+1;
  68. }
  69. else if (dblcpos <= _size)
  70. {
  71. if (_list[cpos].getCost() >= _list[dblcpos].getCost())
  72. pos = dblcpos;
  73. }
  74. if (cpos != pos)
  75. {
  76. temp = _list[cpos];
  77. _list[cpos] = _list[pos];
  78. _list[pos] = temp;
  79. }
  80. else
  81. break;
  82. }
  83. return first;
  84. }
  85. public boolean contains(GeoNode n)
  86. {
  87. if (_size == 0)
  88. return false;
  89. for (int i = 1; i <= _size; i++)
  90. {
  91. if(_list[i].equals(n))
  92. return true;
  93. }
  94. return false;
  95. }
  96. public boolean isEmpty()
  97. {
  98. return _size == 0;
  99. }
  100. }