描述:
给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素
数据范围:
0≤n,m≤10,矩阵中任意元素都满足 |val| ≤100
要求:空间复杂度 O(nm)O(nm) ,时间复杂度 O(nm)O(nm)
实例:
输入:[[1,2,3],[4,5,6],[7,8,9]]
返回:[1,2,3,6,9,8,7,4,5]
输入:[]
返回:[]
import java.util.ArrayList;
public class Solution {
public ArrayList spiralOrder(int[][] matrix) {
ArrayList res = new ArrayList<>();
if(matrix.length == 0) return res;
int count = 0, row = matrix.length, column = matrix[0].length;
int total = row * column;
int up = 0, down = row - 1, left = 0, right = column - 1;
while(count < total){
for(int i = left; i <= right && count < total; i++){
res.add(matrix[up][i]);
count++;
}
up++;
for(int i = up; i <= down && count < total; i++){
res.add(matrix[i][right]);
count++;
}
right--;
for(int i = right; i >= left && count < total; i--){
res.add(matrix[down][i]);
count++;
}
down--;
for(int i = down; i >= up && count < total; i--){
res.add(matrix[i][left]);
count++;
}
left++;
}
return res;
}
}



