/* // 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; } }; */
classSolution { int[][] grid;
public Node construct(int[][] grid) { this.grid = grid; intn= grid.length; return dfs(0, 0, n - 1, n - 1); }
private Node dfs(int a, int b, int c, int d) { booleanflag=true; intt= grid[a][b]; for (inti= a; i <= c && flag; ++i) { for (intj= b; j <= d && flag; ++j) { if (grid[i][j] != t) flag = false; } } if (flag) returnnewNode(t == 1, true); intdx= c - a + 1, dy = d - b + 1; returnnewNode( t == 1, false, dfs(a, b, a + dx / 2 - 1, b + dy / 2 - 1), // 左上 dfs(a, b + dy / 2, a + dx / 2 - 1, d), // 右上 dfs(a + dx / 2, b, c, b + dy / 2 - 1), // 左下 dfs(a + dx / 2, b + dy / 2, c, d) // 右下 ); } }