LeetCode 427. 建立四叉树 (递归dfs \ 矩阵)

思路

根据0,1矩阵,构建四叉树,根据题意就是要判断,当前矩阵中的值是否全部相同

  1. 若矩阵内值相同,也就是只有0或1,则作为叶子节点,叶子结点的值就是这个矩阵的值
  2. 若矩阵内值不相同,也就是有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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值