558四分木交差点
TOPLEFT、topRight、bottomLeftとbottomRight:四分木の各ノードが正確に4つの子ノードを有するツリー・データです。クワッドツリーは、一般的に再帰的に4つの象限又は領域に細分二次元空間を分割するために使用されます。
私たちは、四分木で真/偽の情報を保存したいです。四分木は、N * Nブールグリッドを示すために使用されます。この領域の値が同じになるまで各ノードについて、それが均等に4つのつの子ノードに分割されています。isLeafとval:各ノードは、2つの追加ブール型プロパティを持っています。このノードが葉ノードのisLeafあるとき。ヴァル変数値記憶領域は、葉ノードで表されます。
たとえば、次の2つの四分木AとB:
A:
+-------+-------+ T: true
| | | F: false
| T | T |
| | |
+-------+-------+
| | |
| F | F |
| | |
+-------+-------+
topLeft: T
topRight: T
bottomLeft: F
bottomRight: F
B:
+-------+---+---+
| | F | F |
| T +---+---+
| | T | T |
+-------+---+---+
| | |
| T | F |
| | |
+-------+-------+
topLeft: T
topRight:
topLeft: F
topRight: F
bottomLeft: T
bottomRight: T
bottomLeft: T
bottomRight: F
あなたの仕事は2四分木に基づいて論理的な2分木か(またはと)四分木を返す関数を実装することです。
A:B:C(AまたはB):
+-------+-------+ +-------+---+---+ +-------+-------+
| | | | | F | F | | | |
| T | T | | T +---+---+ | T | T |
| | | | | T | T | | | |
+-------+-------+ +-------+---+---+ +-------+-------+
| | | | | | | | |
| F | F | | T | F | | T | F |
| | | | | | | | |
+-------+-------+ +-------+-------+ +-------+-------+
ヒント:
A及びBは、N * Nサイズのグリッドで表されます。
なお、Nは2の整数乗であることを保証します。
あなたは4分木についての詳細を知りたい場合は、このwikiページを参照することができます。
論理または以下のように定義された:もしAがTrue、またはBが真である、またはAとBがTrueの、「AまたはB」は真です。
/*
// Definition for a QuadTree node.
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
public Node() {}
public Node(boolean _val,boolean _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) {
val = _val;
isLeaf = _isLeaf;
topLeft = _topLeft;
topRight = _topRight;
bottomLeft = _bottomLeft;
bottomRight = _bottomRight;
}
};
*/
class Solution {
//是不是叶子节点
public Node intersect(Node quadTree1, Node quadTree2) {
if(quadTree1.isLeaf && quadTree2.isLeaf){
Node res = new Node(false, false, null, null, null, null);
res.val = quadTree1.val || quadTree2.val;
res.isLeaf = true;
return res;
}
else if(quadTree1.isLeaf && !quadTree2.isLeaf){
if(quadTree1.val){
return quadTree1;
}
else{
return quadTree2;
}
}
else if(quadTree2.isLeaf && !quadTree1.isLeaf){
if(quadTree2.val){
return quadTree2;
}
else{
return quadTree1;
}
}
else{
//都不是叶子结点,就创建结点递归
Node res = new Node(false, false, null, null, null, null);
res.topLeft = intersect(quadTree1.topLeft, quadTree2.topLeft);
res.topRight = intersect(quadTree1.topRight, quadTree2.topRight);
res.bottomLeft = intersect(quadTree1.bottomLeft, quadTree2.bottomLeft);
res.bottomRight = intersect(quadTree1.bottomRight, quadTree2.bottomRight);
//如果都为true,就向下搜索
if(res.topLeft.isLeaf && res.topRight.isLeaf
&& res.bottomLeft.isLeaf && res.bottomRight.isLeaf
&& res.topLeft.val == res.topRight.val
&& res.topRight.val == res.bottomLeft.val
&& res.bottomLeft.val == res.bottomRight.val){
res = res.topLeft;
}
return res;
}
}
}