给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if(matrix == null || matrix.length == 0)
return res;
int rowNum = matrix.length, colNum = matrix[0].length;
int left = 0, right = colNum - 1, top = 0, bot = rowNum - 1;
while(res.size() < rowNum * colNum) {
for(int col = left; col <= right; col++)
res.add(matrix[top][col]);
top++;
if(res.size() < rowNum * colNum) {
for(int row = top; row <= bot; row++)
res.add(matrix[row][right]);
right--;
}
if(res.size() < rowNum * colNum) {
for(int col = right; col >= left; col--)
res.add(matrix[bot][col]);
bot--;
}
if(res.size() < rowNum * colNum) {
for(int row = bot; row >= top; row--)
res.add(matrix[row][left]);
left++;
}
}
return res;
}
}
Q.E.D.