用C語言實現一個2維四叉樹quadtree,具有一定的實際意義。你可以把幾何圖形的索引(用long型的id標識)放到這個樹中(根據最小邊界矩形)。quadtree可以用來快速地區尋找圖形,雖然不是那麼精確,但是畢竟沒有漏掉的。雖然quadtree的效率不如RTree?但是RTree的實現畢竟複雜了些,我會儘快收集整理出RTree的代碼。RTree確實比QuadTree好的多?(起碼RTree很時髦啊!)
標頭檔如下:
/*
* quadtree.h
* Quad tree structure -- for spatial quick searching
* cheungmine
* Oct. 5, 2007. All rights reserved.
*/
#ifndef QUADTREE_H_INCLUDED
#define QUADTREE_H_INCLUDED
#include "unistd.h"
#include "list.h"
#define QUAD_SUBNODES 4
#define QBOX_OVERLAP_MAX 0.4
#define QBOX_OVERLAP_MIN 0.02
#define QTREE_DEPTH_MAX 8
#define QTREE_DEPTH_MIN 4
#define QUADRANT_BITS 3
/* a quadrant defined below:
NW(1) | NE(0)
-----------|-----------
SW(2) | SE(3)
*/
typedef enum
{
NE = 0,
NW = 1,
SW = 2,
SE = 3
}QuadrantEnum;
/* a box defined below:
_____max
|__|__|
|__|__|
min
*/
typedef struct _quadbox_t
{
double _xmin,
_ymin,
_xmax,
_ymax;
}quadbox_t;
/* quad node */
typedef struct _quadnode_t
{
quadbox_t _box; /* node bound box */
list_t *_lst; /* node data list */
struct _quadnode_t *_sub[QUAD_SUBNODES]; /* pointer to subnodes of this node */
}quadnode_t;
/* quad tree */
typedef struct _quadtree_t
{
quadnode_t *_root;
int _depth; /* max depth of tree: 0-based */
float _overlap; /* overlapped ratio of quanbox */
}quadtree_t;
/*=============================================================================
Public Functions
=============================================================================*/
/* creates a quadtree and returns a pointer to it */
extern quadtree_t*
quadtree_create (quadbox_t box,
int depth, /* 4~8 */
float overlap /* 0.02 ~ 0.4 */
);
/* destroys a quad tree and free all memory */
extern void
quadtree_destroy (IN quadtree_t *qtree
);
/* inserts a node identified by node_key into a quadtree, returns the node quadtree encoding */
extern quadnode_t *
quadtree_insert (IN quadtree_t *qtree,
IN long node_key,
IN quadbox_t *node_box
);
/* searches nodes inside search_box */
extern void
quadtree_search (IN const quadtree_t *qtree,
IN quadbox_t *search_box,
OUT list_t *results_list
);
#endif // QUADTREE_H_INCLUDED