- Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0427-construct-quad-tree.rb
44 lines (38 loc) · 1.18 KB
/
0427-construct-quad-tree.rb
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
# frozen_string_literal: true
# 427. Construct Quad Tree
# https://leetcode.com/problems/construct-quad-tree
# Definition for a QuadTree node.
# class Node
# attr_accessor :val, :isLeaf, :topLeft, :topRight, :bottomLeft, :bottomRight
# def initialize(val=false, isLeaf=false, topLeft=nil, topRight=nil, bottomLeft=nil, bottomRight=nil)
# @val = val
# @isLeaf = isLeaf
# @topLeft = topLeft
# @topRight = topRight
# @bottomLeft = bottomLeft
# @bottomRight = bottomRight
# end
# end
# @param {Integer[][]} grid
# @return {Node}
defconstruct(grid,r=0,c=0,length=grid.length)
ifsame?(grid,r,c,length)
returnNode.new(grid[r][c] == 1 ? true : false,true)
end
node=Node.new(true,false)
node.topLeft=construct(grid,r,c,length / 2)
node.topRight=construct(grid,r,c + length / 2,length / 2)
node.bottomLeft=construct(grid,r + length / 2,c,length / 2)
node.bottomRight=construct(grid,r + length / 2,c + length / 2,length / 2)
node
end
defsame?(grid,r,c,n)
foriinr..r + n - 1
forjinc..c + n - 1
ifgrid[i][j] != grid[r][c]
returnfalse
end
end
end
true
end