leetcode427. Construct Quad Tree

題目要求

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:


It can be divided according to the definition above:

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 * .

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);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章