leetcode427. Construct Quad Tree

2019-10-30 00:00:00 tree Construct leetcode427

题目要求

We want to use quad trees to store an N x N boolean grid. Each cell in the grid can only be true or false. The root node represents the whole grid. For each node, it will be subdivided into four children nodes until the values in the region it represents are all the same.

Each node has another two boolean attributes : isLeaf and val . isLeaf is true if and only if the node is a leaf node. The val attribute for a leaf node contains the value of the region it represents.

Your task is to use a quad tree to represent a given grid. The following example may help you understand the problem better:

Given the 8 x 8 grid below, we want to construct the corresponding quad tree:

《leetcode427. Construct Quad Tree》
It can be divided according to the definition above:

《leetcode427. Construct Quad Tree》

The corresponding quad tree should be as following, where each node is represented as a(isLeaf, val)pair.

For the non-leaf nodes, val can be arbitrary, so it is represented as * .

《leetcode427. Construct Quad Tree》

Note:

  1. N is less than 1000 and guaranteened to be a power of 2.
  2. If you want to know more about the quad tree, you can refer to its wiki.

要求用一个四叉树来表示一个N*N的矩阵,如果该矩阵中的值为全1,则该节点的val值为true,否则每次将矩阵按照中间点四等分,并分别判断每一个子矩阵是否val为true。

思路和代码

这里采用深度优先遍历的思想,即每次将矩阵进行四等分,并分别判断每个子矩阵是否是全1的子矩阵。如果4个子矩阵均为全1的子矩阵,则将四个矩阵合并为一个父矩阵,否则分别记录每个子矩阵的结果。

代码如下:

    public Node construct(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return null;
        }
        return construct(grid, 0, 0, grid.length);
    }

    public Node construct(int[][] grid, int topRow, int topColumn, int length) {
        if (length == 1) {
            return new Node(grid[topRow][topColumn] == 1, true, null, null, null, null);
        }
        Node topLeft = construct(grid, topRow, topColumn, length/2);
        Node topRight = construct(grid, topRow, topColumn+length/2, length/2);
        Node bottomLeft = construct(grid, topRow+length/2, topColumn, length/2);
        Node bottomRight = construct(grid, topRow+length/2, topColumn+length/2, length/2);
        if (topLeft.val && topRight.val && bottomLeft.val && bottomRight.val) {
            return new Node(true, true, null, null, null, null);
        }else if (!topLeft.val && !topRight.val && !bottomLeft.val && !bottomRight.val && topLeft.isLeaf && topRight.isLeaf && bottomLeft.isLeaf && bottomRight.isLeaf) {
            return new Node(false, true, null, null, null, null);
        }
        return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight);
    }
    原文作者:raledong
    原文地址: https://segmentfault.com/a/1190000020852659
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章