I'm having trouble accounting for the odd input cases in the below problem:Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
My code works on all the bigger test cases, but fails for things like
[[6,9,7]]
and I'm not sure how to construct my code to handle these inputs. Anyone have ideas?
def spiral_order(matrix)
return nil if matrix.nil?
return [] if matrix.empty?
m = matrix.length - 1
n = matrix.first.length - 1
start_col = start_row = 0
end_col = n
end_row = m
visited = []
iter = 0
until start_row > end_row && start_col > end_col
until iter > end_col
visited << matrix[start_row][iter]
iter+=1
end
start_row += 1
iter = start_row
until iter > end_row
visited << matrix[iter][end_col]
iter += 1
end
end_col -= 1
iter = end_col
until iter < start_col
visited << matrix[end_row][iter]
iter-=1
end
end_row -= 1
iter = end_row
until iter < start_row
visited << matrix[iter][start_col]
iter -= 1
end
start_col += 1
iter = start_col
end
visited
end
On the [6,9,7] I'm getting a nil error on line 17. I know the entire loop runs twice (this in itself shouldn't be the case because I'm incrementing the start limits and decrementing the end limits) but I'm struggling to create code that works for both regular inputs and the strange cases without throwing in a ton of conditionals to handle more unusual cases.