forked from javadev/LeetCode-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
85 lines (79 loc) · 2.75 KB
/
Solution.java
File metadata and controls
85 lines (79 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package g0401_0500.s0427_construct_quad_tree;
// #Medium #Array #Tree #Matrix #Divide_and_Conquer #Top_Interview_150_Divide_and_Conquer
// #2025_03_09_Time_0_ms_(100.00%)_Space_44.55_MB_(62.63%)
/*
// Definition for a QuadTree node.
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
public Node() {
this.val = false;
this.isLeaf = false;
this.topLeft = null;
this.topRight = null;
this.bottomLeft = null;
this.bottomRight = null;
}
public Node(boolean val, boolean isLeaf) {
this.val = val;
this.isLeaf = isLeaf;
this.topLeft = null;
this.topRight = null;
this.bottomLeft = null;
this.bottomRight = null;
}
public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {
this.val = val;
this.isLeaf = isLeaf;
this.topLeft = topLeft;
this.topRight = topRight;
this.bottomLeft = bottomLeft;
this.bottomRight = bottomRight;
}
};
*/
public class Solution {
public Node construct(int[][] grid) {
return optimizedDfs(grid, 0, 0, grid.length);
}
private Node optimizedDfs(int[][] grid, int rowStart, int colStart, int len) {
int zeroCount = 0;
int oneCount = 0;
for (int row = rowStart; row < rowStart + len; row++) {
boolean isBreak = false;
for (int col = colStart; col < colStart + len; col++) {
if (grid[row][col] == 0) {
zeroCount++;
} else {
oneCount++;
}
if (oneCount > 0 && zeroCount > 0) {
// We really no need to scan all.
// Once we know there are both 0 and 1 then we can break.
isBreak = true;
break;
}
}
if (isBreak) {
break;
}
}
if (oneCount > 0 && zeroCount > 0) {
int midLen = len / 2;
Node topLeft = optimizedDfs(grid, rowStart, colStart, midLen);
Node topRight = optimizedDfs(grid, rowStart, colStart + midLen, midLen);
Node bottomLeft = optimizedDfs(grid, rowStart + midLen, colStart, midLen);
Node bottomRight = optimizedDfs(grid, rowStart + midLen, colStart + midLen, midLen);
boolean isLeaf = false;
return new Node(true, isLeaf, topLeft, topRight, bottomLeft, bottomRight);
} else {
boolean resultVal = oneCount > 0;
boolean isLeaf = true;
return new Node(resultVal, isLeaf);
}
}
}