From 3a982c9b0c221ecb2bf9e6728ec910209b1d2ee6 Mon Sep 17 00:00:00 2001 From: hanzhang ma Date: Tue, 11 Jun 2024 15:06:26 +0200 Subject: [PATCH] 427 dfs --- 427-240611-pass/main.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 427-240611-pass/main.py diff --git a/427-240611-pass/main.py b/427-240611-pass/main.py new file mode 100644 index 0000000..801f534 --- /dev/null +++ b/427-240611-pass/main.py @@ -0,0 +1,41 @@ +""" +# 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': + n = len(grid) + def check_is_leaf(row_start,row_end,column_start,column_end): + x = grid[row_start][column_start] + for i in range(row_start, row_end + 1): + for j in range(column_start, column_end + 1): + if grid[i][j] != x: + return 0 + return 1 + def dfs(dim, row, column,node): + isLeaf = check_is_leaf(row,row+dim -1 , column, column + dim - 1) + node.isLeaf= isLeaf + if isLeaf==1: + node.val=grid[row][column] + else: + node.val = 1 + top_left = Node() + node.topLeft = dfs(dim // 2, row, column, top_left) + top_right = Node() + node.topRight = dfs(dim // 2, row, column + dim // 2, top_right) + bottom_left = Node() + node.bottomLeft = dfs(dim // 2, row + dim // 2, column, bottom_left) + bottom_right = Node() + node.bottomRight = dfs(dim // 2, row + dim // 2, column + dim // 2, bottom_right) + return node + root = Node() + root = dfs(n,0,0,root) + return root \ No newline at end of file