Thursday, May 23, 2013

quadtree (C++)

问题1 : 为这个 quadtree里面的 node 设计 data structure

然后的问题是关于两个 quadtree 的 intersection, 有两个 quadtree, 它们描述的 
image 是两个相同的 area
比如 都是 [0 1] x [0 1] 这个相同的二维区域的image.

问题二: 写一个函数,返回两个 quadtree的intersection,

这个intersection的规则是: 如果一个区域在 第一个quadtree 里面是
白的,这个相同的区域在 第二个 quadtree里面是黑的,那么intersection
就是白的,简单的说白是 0, 黑是 1, intersection就是两个bit 的 AND
-------------------
//color: 0 means white, 1 means black, 2 means mixed.
struct Qnode{
private:
  int color; 
  Qnode *children;
public:
  Qnode(int c){color = c;};




Qnode *intersection(Qnode *first, Qnode *second){
   if(first == NULL && second == NULL)
 // if both nodes are mixed
  if(first->color == 2 && second->color == 2){
    Qnode *root = new Qnode(2);
    Qnode *newchildren = new Qnode[4];
    int count = 0;
    for(i = 0; i < 4; i++){
    newchildren[i] = intersection(first->children[i], second->children[i]); 
    if(newchildren[i]->color == 0) count++;  
    }
   if(count == 4){
     root->color = 0;
     delete[] newchildren;
   }  
 } 

//if at least one is while
else if(first->color == 0 || second->color == 0)  
  Qnode *root = new Qnode(0);
  root->children = NULL;


//if one black one mixed or two blacks
else if(first->color == 1) Qnode *root =clone(second);
else (second->color == 1) Qnode *root = clone(first);

return root;
 }

Qnode *clone(Qnode *quad){
  if(quad == NULL) return Null;
  Qnode *root = new Qnode(quad->color);
  if(!quad->children) root->children == NULL; 
  else 
for(int i = 0; i < 4; i++){
 root->children[i] = clone(quad->children[i]);
}

return root;
}



No comments:

Post a Comment