forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
65 lines (59 loc) · 1.86 KB
/
Solution.java
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
/*
// 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;
}
};
*/
class Solution {
public Node construct(int[][] grid) {
return dfs(0, 0, grid.length - 1, grid[0].length - 1, grid);
}
private Node dfs(int a, int b, int c, int d, int[][] grid) {
int zero = 0, one = 0;
for (int i = a; i <= c; ++i) {
for (int j = b; j <= d; ++j) {
if (grid[i][j] == 0) {
zero = 1;
} else {
one = 1;
}
}
}
boolean isLeaf = zero + one == 1;
boolean val = isLeaf && one == 1;
Node node = new Node(val, isLeaf);
if (isLeaf) {
return node;
}
node.topLeft = dfs(a, b, (a + c) / 2, (b + d) / 2, grid);
node.topRight = dfs(a, (b + d) / 2 + 1, (a + c) / 2, d, grid);
node.bottomLeft = dfs((a + c) / 2 + 1, b, c, (b + d) / 2, grid);
node.bottomRight = dfs((a + c) / 2 + 1, (b + d) / 2 + 1, c, d, grid);
return node;
}
}