-
Notifications
You must be signed in to change notification settings - Fork 0
/
59_spiral_matrix_ii.rb
71 lines (63 loc) · 1.15 KB
/
59_spiral_matrix_ii.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
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
# frozen_string_literal: true
# https://leetcode.com/problems/spiral-matrix-ii/
# @param {Integer} n
# @return {Integer[][]}
def generate_matrix(n)
i = 0
j = 0
up = 0
right = 1
left = 2
down = 4
up_side = 0
right_side = n
left_side = -1
down_side = n
direction = right
value = 0
result = ::Array.new(n) { ::Array.new(n) { nil } }
while value < n * n
if direction == up
while i > up_side
value += 1
result[i][j] = value
i -= 1
end
i += 1
j += 1
up_side += 1
direction = right
elsif direction == right
while j < right_side
value += 1
result[i][j] = value
j += 1
end
i += 1
j -= 1
right_side -= 1
direction = down
elsif direction == left
while j > left_side
value += 1
result[i][j] = value
j -= 1
end
i -= 1
j += 1
left_side += 1
direction = up
else
while i < down_side
value += 1
result[i][j] = value
i += 1
end
i -= 1
j -= 1
down_side -= 1
direction = left
end
end
result
end