给定一个包含 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]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:一圈一圈加,注意数组越界以及题目规则
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix.length == 0 || matrix == null) return new ArrayList();//数组为空时
int iLength = matrix.length;
int jLength = matrix[0].length;
int step = iLength * jLength;//共添加多少个元素
ArrayList<Integer> list = new ArrayList<>(step);
int cur = 0, i = 0, j = 0;
int ii = 0, jj = 0;
while (cur < step) {//每次循环代表一圈
if (cur > 0) {
jLength -= 1;
iLength -= 1;
ii += 1;//避免将添加过的元素继续添加
jj += 1;
}
while (cur < step && j < jLength) {
list.add(matrix[i][j++]);
cur++;
}
j--;//避免数组越界,下同
i++;
while (cur < step && i < iLength) {
list.add(matrix[i++][j]);
cur++;
}
i--;
j--;
while (cur < step && j >= jj) {
list.add(matrix[i][j--]);
cur++;
}
j++;
i--;
while (cur < step && i > ii) {
list.add(matrix[i--][j]);
cur++;
}
i++;
j++;
}
return list;
}