Skip to content

Commit 92ec5e7

Browse files
authored
Create 0427-construct-quad-tree.kt
1 parent a291d75 commit 92ec5e7

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Diff for: kotlin/0427-construct-quad-tree.kt

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* Definition for a QuadTree node.
3+
* class Node(var `val`: Boolean, var isLeaf: Boolean) {
4+
* var topLeft: Node? = null
5+
* var topRight: Node? = null
6+
* var bottomLeft: Node? = null
7+
* var bottomRight: Node? = null
8+
* }
9+
*/
10+
11+
class Solution {
12+
fun construct(grid: Array<IntArray>): Node? {
13+
14+
fun dfs(n: Int, r: Int, c: Int): Node? {
15+
var allSame = true
16+
17+
for(i in 0 until n) {
18+
for(j in 0 until n) {
19+
if(grid[r][c] != grid[r + i][c + j]) {
20+
allSame = false
21+
break
22+
}
23+
}
24+
}
25+
26+
if(allSame) return Node(if(grid[r][c] == 1) true else false, true)
27+
28+
val nextN = n/2
29+
val topLeft = dfs(nextN, r, c)
30+
val topRight = dfs(nextN, r, c + nextN)
31+
val bottomLeft = dfs(nextN, r + nextN, c)
32+
val bottomRight = dfs(nextN, r + nextN, c + nextN)
33+
34+
val node = Node(false, false)
35+
node.topLeft = topLeft
36+
node.topRight = topRight
37+
node.bottomLeft = bottomLeft
38+
node.bottomRight = bottomRight
39+
return node
40+
}
41+
42+
return dfs(grid.size, 0, 0)
43+
}
44+
}

0 commit comments

Comments
 (0)