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:
You should return [1,2,3,6,9,8,7,4,5].
解法1:O(M*N) Time, O(1) Space
运用分层处理的思想。一般情况,每一层有4条边组成,顺序是按照right, down, left, up。而且每一层的最后一行和第一行, 最后一列和第一列是对应关系。意思是说如果我们从第i行开始,那么与之对应的最后一行便是m - 1 - i, 列野同理。
那么层数有多少呢?这是又行数和列数决定的. level = (min(row, col) + 1) / 2
还有一个坑是对于单行或者单列的处理需要单独计算。
Java