Skip to content

Commit

Permalink
Ruby Solution for Spiral Matrix
Browse files Browse the repository at this point in the history
  • Loading branch information
saip7795 committed Jan 11, 2023
1 parent eff3535 commit a11b52c
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions ruby/0054-spiral-matrix.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
def spiral_order(matrix)
result = []
left = 0
right = matrix[0].length
top = 0
bottom = matrix.length

while left < right && top < bottom

(left..right-1).each do |i|
result.append(matrix[top][i])
end

top +=1

(top..bottom-1).each do |i|
result.append(matrix[i][right-1])
end

right -=1

break unless (left < right && top < bottom)

(right-1).downto(left).each do |i|
result.append(matrix[bottom-1][i])
end

bottom -=1

(bottom-1).downto(top).each do |i|
result.append(matrix[i][left])
end

left +=1

end

return result
end

0 comments on commit a11b52c

Please sign in to comment.