思路
根据0,1矩阵,构建四叉树,根据题意就是要判断,当前矩阵中的值是否全部相同
- 若矩阵内值相同,也就是只有0或1,则作为叶子节点,叶子结点的值就是这个矩阵的值
- 若矩阵内值不相同,也就是有0也有1,则该矩阵被划分为4个部分,继续判断子矩阵,所以可以递归进行。
根据分析,定义深度优先遍历函数:
dfs(grid, r0, c0, r1, c1): 构造以[r0,c0]为左上,[r1,c1]为右下的矩阵所表示的四叉树的根节点。
每个矩阵都可以划分为这样的四个,可以使用递归深搜的方式,对矩阵进行判断。
代码实现(java)
/*
// 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() {
this.val = false;
this.isLeaf = false;
this.topLeft = null;
this.topRight = null;
this.bottomLeft = null;
this.bottomRight = null;
}
public Node(boolean val, boolean isLeaf) {
this.val = val;
this.isLeaf = isLeaf;
this.topLeft = null;
this.topRight = null;
this.bottomLeft = null;
this.bottomRight = null;
}
public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {
this.val = val;
this.isLeaf = isLeaf;
this.topLeft = topLeft;
this.topRight = topRight;
this.bottomLeft = bottomLeft;
this.bottomRight = bottomRight;
}
};
*/
class Solution {
public Node construct(int[][] grid) {
return dfs(grid, 0, 0, grid.length, grid.length);
}
public Node dfs(int[][] grid, int r0, int c0, int r1, int c1) {
// 矩阵里的数都相等
boolean isSamVal = true;
// 判断矩阵中的值是否相同
for(int i = r0; i < r1; i++) {
for(int j = c0; j < c1; j++) {
// 如果矩阵中的值不与grid[r0][c0]首元素相同
// 修改为 false
if(grid[i][j] != grid[r0][c0]) {
isSamVal = false;
break;
}
if(!isSamVal) break;
}
}
// 都相同,则定义为叶子结点
if(isSamVal) {
// 叶子结点
return new Node(grid[r0][c0] == 1, true);
}
// 否则,就是中间结点,继续递归dfs,对矩阵进行四分切割,再次判断
Node cur = new Node(
true,
false,
dfs(grid, r0, c0, ((r0 + r1) / 2), ((c0 + c1) / 2)),
dfs(grid, r0, ((c0 + c1) / 2), ((r0 + r1) / 2), c1),
dfs(grid, ((r0 + r1) / 2), c0, r1, ((c0 + c1) / 2)),
dfs(grid, ((r0 + r1) / 2), ((c0 + c1) / 2), r1, c1)
);
return cur;
}
}