Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1991 from saip7795/sp/spiral-matrix
Browse files Browse the repository at this point in the history
Create: 0054-Spiral-Matrix.rb
  • Loading branch information
tahsintunan authored Jan 11, 2023
2 parents d346853 + a11b52c commit a6fdcdc
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 a6fdcdc

Please sign in to comment.