Skip to content

Commit a6fdcdc

Browse files
authored
Merge pull request #1991 from saip7795/sp/spiral-matrix
Create: 0054-Spiral-Matrix.rb
2 parents d346853 + a11b52c commit a6fdcdc

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Diff for: ruby/0054-spiral-matrix.rb

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
def spiral_order(matrix)
2+
result = []
3+
left = 0
4+
right = matrix[0].length
5+
top = 0
6+
bottom = matrix.length
7+
8+
while left < right && top < bottom
9+
10+
(left..right-1).each do |i|
11+
result.append(matrix[top][i])
12+
end
13+
14+
top +=1
15+
16+
(top..bottom-1).each do |i|
17+
result.append(matrix[i][right-1])
18+
end
19+
20+
right -=1
21+
22+
break unless (left < right && top < bottom)
23+
24+
(right-1).downto(left).each do |i|
25+
result.append(matrix[bottom-1][i])
26+
end
27+
28+
bottom -=1
29+
30+
(bottom-1).downto(top).each do |i|
31+
result.append(matrix[i][left])
32+
end
33+
34+
left +=1
35+
36+
end
37+
38+
return result
39+
end

0 commit comments

Comments
 (0)