题目描述
给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。
示例
输入
[[1,2,3],[4,5,6],[7,8,9]]
返回值
[1,2,3,6,9,8,7,4,5]
public class Solution {
public static ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<>();
if(matrix == null || matrix.length < 1) return list;
int m = matrix.length, n = matrix[0].length;
int left = 0, top = 0, right = n-1, down = m-1;
int count = m * n;
int index = 0;
while (index < count) {
// 左移
int l = left;
while(l <= right && index < count) { // 1,2,3
list.add(matrix[top][l++]);
index++;
}
top++;
// 下移
int t = top;
while(t <= down && index < count) { // 6,9
list.add(matrix[t++][right]);
index++;
}
right--;
// 左移
int r = right;
while(r >= left && index < count) {
list.add(matrix[down][r--]);
index++;
}
down--;
// 上移
int d = down;
while (d >= top && index < count) {
list.add(matrix[d--][left]);
index++;
}
left++;
}
return list;
}
}