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]
.
注意矩阵为空的情况
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
int row = matrix.length;
ArrayList<Integer> result = new ArrayList<Integer>();
if(row==0) //矩阵为空的情况
{
return result;
}
int col = matrix[0].length; //如果矩阵为空,matrix[0]不能访问
int rowstart = 0, rowend = row, colstart = 0, colend = col;
int num = 0;
while (num != row * col) {
// 上行
for (int i = colstart; i < colend; i++) {
result.add(matrix[rowstart][i]);
num++;
if (num == row * col)
return result; //直接返回结果
}
rowstart++;
// 右列
for (int i = rowstart; i < rowend; i++) {
result.add(matrix[i][colend - 1]);
num++;
if (num == row * col)
return result;
}
colend--;
// 下行
for (int i = colend - 1; i >= colstart; i--) {
result.add(matrix[rowend - 1][i]);
num++;
if (num == row * col)
return result;
}
rowend--;
// 左列
for (int i = rowend - 1; i >= rowstart; i--) {
result.add(matrix[i][colstart]);
num++;
if (num == row * col)
return result;
}
colstart++;
}
return result;
}
}