LeetCode 427 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 valisLeaf 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.

题目分析及思路

需要使用quad trees来存储 N x N的布尔值网格,每个网格只能是true或false。根结点表示整个网格。对于每一个结点,要求将自身平均分成四分,直到每一份的值都相等为止。每一个结点还有另外两个布尔属性isLeaf和val。isLeaf是True当且仅当这个结点是叶结点。val则是表示当前叶结点的值,若不是叶结点,则用“*”表示。可以先写一个函数来判断这个区域的值是否相同,之后用递归的方法求解,条件是该结点是叶结点。

python代码 

"""

# Definition for a QuadTree node.

class Node:

    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):

        self.val = val

        self.isLeaf = isLeaf

        self.topLeft = topLeft

        self.topRight = topRight

        self.bottomLeft = bottomLeft

        self.bottomRight = bottomRight

"""

class Solution:

    def construct(self, grid: List[List[int]]) -> 'Node':

        def isthesame(grid):

            e = set()

            for r in range(len(grid)):

                for c in range(len(grid)):

                    e.add(grid[r][c])

            if len(e) == 1 and 1 in e:

                return True

            elif len(e) == 1 and 0 in e:

                return False

            else:

                return '*'

        if isthesame(grid) == True:

            return Node(True, True, None, None, None, None)

        elif isthesame(grid) == False:

            return Node(False, True, None, None, None, None)

        else:

            l = len(grid)

            mid = l // 2

            topleft = [[grid[i][j] for j in range(mid)] for i in range(mid)]

            topright = [[grid[i][j] for j in range(mid, l)] for i in range(mid)]

            bottomleft = [[grid[i][j] for j in range(mid)] for i in range(mid, l)]

            bottomright = [[grid[i][j] for j in range(mid, l)] for i in range(mid, l)]

            return Node('*', False, self.construct(topleft), self.construct(topright), self.construct(bottomleft), self.construct(bottomright))

        

            

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10569996.html
今日推荐