Spiral Matrix

Traverse a 2D matrix in spiral order starting from the top-left corner.

Code

Algorithms
m = matrix
result = []
top, bottom, left, right = 0, m.length - 1, 0, m[0].length - 1
while top <= bottom && left <= right
  (left..right).each { |i| result << m[top][i] }
  top += 1
  (top..bottom).each { |i| result << m[i][right] }
  right -= 1
  if top <= bottom
    (right).downto(left).each { |i| result << m[bottom][i] }
    bottom -= 1
  end
  if left <= right
    (bottom).downto(top).each { |i| result << m[i][left] }
    left += 1
  end
end
return result

Parameters

2D matrix

Server

More Ruby Snippets