1
+ namespace LeetCodeSolutions . DivideAndConquer ;
2
+
3
+ /// <summary>
4
+ /// https://leetcode.com/problems/construct-quad-tree/
5
+ /// </summary>
6
+ public class ConstructQuadTree
7
+ {
8
+ public Node Construct ( int [ ] [ ] grid )
9
+ {
10
+ // Start the recursive construction from the entire grid
11
+ return Construct ( grid , 0 , 0 , grid . Length ) ;
12
+ }
13
+
14
+ public Node Construct ( int [ ] [ ] grid , int i , int j , int length )
15
+ {
16
+ // Check if the current section has all the same values
17
+ if ( IsSame ( grid , i , j , length ) )
18
+ {
19
+ // Create a leaf node with the value of the first cell in this section
20
+ return new Node ( grid [ i ] [ j ] == 1 , true ) ;
21
+ }
22
+ else
23
+ {
24
+ // Create a non-leaf node
25
+ Node node = new Node ( false , false ) ;
26
+
27
+ // Divide the current section into four quadrants and construct nodes for each
28
+ int halfLength = length / 2 ;
29
+ node . topLeft = Construct ( grid , i , j , halfLength ) ;
30
+ node . topRight = Construct ( grid , i , j + halfLength , halfLength ) ;
31
+ node . bottomLeft = Construct ( grid , i + halfLength , j , halfLength ) ;
32
+ node . bottomRight = Construct ( grid , i + halfLength , j + halfLength , halfLength ) ;
33
+
34
+ return node ;
35
+ }
36
+ }
37
+ private bool IsSame ( int [ ] [ ] grid , int row , int column , int length )
38
+ {
39
+ // Get the value of the first cell to compare against
40
+ int value = grid [ row ] [ column ] ;
41
+
42
+ // Check every cell in the section
43
+ for ( int i = row ; i < row + length ; i ++ )
44
+ {
45
+ for ( int j = column ; j < column + length ; j ++ )
46
+ {
47
+ // If any cell has a different value, return false
48
+ if ( grid [ i ] [ j ] != value )
49
+ {
50
+ return false ;
51
+ }
52
+ }
53
+ }
54
+
55
+ // All cells have the same value
56
+ return true ;
57
+ }
58
+ }
59
+
60
+ /// <summary>
61
+ /// Definition for a Quadtree node.
62
+ /// </summary>
63
+ public class Node
64
+ {
65
+ public bool val ;
66
+ public bool isLeaf ;
67
+ public Node topLeft ;
68
+ public Node topRight ;
69
+ public Node bottomLeft ;
70
+ public Node bottomRight ;
71
+
72
+ public Node ( bool _val = false , bool _isLeaf = false )
73
+ {
74
+ val = _val ;
75
+ isLeaf = _isLeaf ;
76
+ topLeft = null ;
77
+ topRight = null ;
78
+ bottomLeft = null ;
79
+ bottomRight = null ;
80
+ }
81
+ }
0 commit comments