7 lines solution in Ruby, concise and recursively.


  • 0
    A
    def spiral_order(matrix)
      return matrix.flatten if matrix.size < 2 || matrix[0].size < 2
      result, stack = matrix.shift, []
      (matrix.size-1).times do |i|
        stack << matrix[i].shift
        result << matrix[i].pop
      end
      result + matrix.pop.reverse + stack.reverse + spiral_order(matrix)
    end

  • 1

    Modified it a bit...

    def spiral_order(matrix)
      return matrix.flatten if matrix.size < 2 || matrix[0].size < 2
      matrix.shift + matrix.map(&:pop) + matrix.pop.reverse + matrix.map(&:shift).reverse + spiral_order(matrix)
    end
    

    Or:

    def spiral_order(matrix)
      return matrix.flatten if matrix.size < 2 || matrix[0].size < 2
      matrix.shift + matrix.map(&:pop) + (matrix.map(&:shift) + matrix.pop).reverse + spiral_order(matrix)
    end

  • 0
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.