/* add a coordinate pair in the heap so that the heap root always contains the minimum A* score */ static void heap_add(TCOD_path_data_t *path, TCOD_list_t heap, int x, int y) { /* append the new value to the end of the heap */ uintptr off=x+y*path->w; TCOD_list_push(heap,(void *)off); /* bubble the value up to its real position */ heap_sift_up(path,heap); }
/** * @brief 添加一个元素. * @param[in] h 堆对象的指针 * @param[in] x 要添加的元素 * @return 无 */ void heap_push(heap_t *h, const heap_elem_t x) { if(h->size == h->capacity) { /* 已满,重新分配内存 */ heap_elem_t* tmp = (heap_elem_t*)realloc(h->elems, h->capacity * 2 * sizeof(heap_elem_t)); h->elems = tmp; h->capacity *= 2; } h->elems[h->size] = x; h->size++; heap_sift_up(h, h->size - 1); }
/** Inserta al heap un puntero con key dada. Retorna el nodo donde quedó */ size_t* heap_insert(Heap* heap, void* pointer, int key) { /* Almacenamos la informacion en el nodo */ heap -> array[heap -> count].content = pointer; heap -> array[heap -> count].key = key; /* Obtenemos el puntero de su indice */ size_t* index = heap -> array[heap -> count].index; /* Marcamos como que hay un elemento más */ heap -> count++; /* Lo hacemos subir a donde le corresponde */ heap_sift_up(heap, *index); /* Retornamos el indice del nodo */ return index; }
/* this is the slow part, when we change the heuristic of a cell already in the heap */ static void heap_reorder(TCOD_path_data_t *path, uint32 offset) { uintptr *array=(uintptr *)TCOD_list_begin(path->heap); uintptr *end=(uintptr *)TCOD_list_end(path->heap); uintptr *cur=array; /* find the node corresponding to offset ... SLOW !! */ while (cur != end) { if (*cur == offset ) break; cur++; } if ( cur == end ) return; /* remove it... SLOW !! */ TCOD_list_remove_iterator(path->heap,(void **)cur); /* put it back on the heap */ TCOD_list_push(path->heap,(void *)(uintptr)offset); /* bubble the value up to its real position */ heap_sift_up(path,path->heap); }
/** Actualiza la key y posicion del nodo en index */ void heap_update_key(Heap* heap, size_t index, int key) { /* Si la key es la misma, no hay nada que hacer */ if(heap -> array[index].key == key) return; /* Si la nueva es mayor a la antigua */ if(key > heap -> array[index].key) { heap -> array[index].key = key; heap_sift_up(heap, index); } /* Si la nueva es menor */ else { heap -> array[index].key = key; heap_sift_down(heap, index); } }