replaceHa.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /***********************************************************
  2. *
  3. * replaceHa.c (for spread)
  4. * This routine is to delete a cell in a heap.
  5. * It 1) searches the cell backward and sequentially from
  6. * the heap (if not found, returns a error message),
  7. * 2) repalce that cell with the new min_cost and
  8. * restore a heap order.
  9. *
  10. ************************************************************/
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <grass/gis.h>
  14. #include "costHa.h"
  15. #include "local_proto.h"
  16. void
  17. replaceHa(float new_min_cost, float angle, int row, int col,
  18. struct costHa *heap, long *heap_len)
  19. {
  20. long i, smaller_child = 0;
  21. G_debug(4, "in replaceHa()");
  22. if (*heap_len < 1)
  23. G_fatal_error("Programming ERROR: can't delete a cell from an empty list");
  24. /* search the cell with row and col from the heap */
  25. for (i = *heap_len; i >= 0; i--) {
  26. if (heap[i].row == row && heap[i].col == col)
  27. break;
  28. }
  29. if (i == 0)
  30. G_fatal_error("Programming ERROR: can't find the old_cell from the list");
  31. /* replace this cell, fix the heap */
  32. /*take care upward */
  33. G_debug(4, "in replaceHa() before first while");
  34. while (i > 1 && new_min_cost < heap[i / 2].min_cost) {
  35. heap[i].min_cost = heap[i / 2].min_cost;
  36. heap[i].angle = heap[i / 2].angle;
  37. heap[i].row = heap[i / 2].row;
  38. heap[i].col = heap[i / 2].col;
  39. i = i / 2;
  40. }
  41. /*take care downward */
  42. if (2 * i <= *heap_len)
  43. smaller_child = 2 * i;
  44. if ((2 * i < *heap_len) &&
  45. (heap[2 * i].min_cost > heap[2 * i + 1].min_cost))
  46. smaller_child++;
  47. G_debug(4, "in replaceHa() before second while. smaller_child=%ld",
  48. smaller_child);
  49. while ( (smaller_child <= *heap_len) && (smaller_child > 0) &&
  50. (new_min_cost > heap[smaller_child].min_cost)) {
  51. heap[i].min_cost = heap[smaller_child].min_cost;
  52. heap[i].angle = heap[smaller_child].angle;
  53. heap[i].row = heap[smaller_child].row;
  54. heap[i].col = heap[smaller_child].col;
  55. i = smaller_child;
  56. smaller_child = 2 * i;
  57. if ((2 * i < *heap_len) &&
  58. (heap[2 * i].min_cost > heap[2 * i + 1].min_cost))
  59. smaller_child++;
  60. }
  61. /*now i is the right position */
  62. heap[i].min_cost = new_min_cost;
  63. heap[i].angle = angle;
  64. heap[i].row = row;
  65. heap[i].col = col;
  66. G_debug(4, "replaceHa() done");
  67. return;
  68. }