给定一个包含 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 ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> rst = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0) {
return rst;
}
int rows = matrix.length;
int cols = matrix[0].length;
// count 代表第几层,即从第 count 行,count 列开始
int count = 0;
// 注意判断条件的写法,记住
while (count * 2 < rows && count * 2 < cols) {
// 从左到右打印一行
for (int i = count; i < cols - count; i++) {
rst.add(matrix[count][i]);
}
// 从上到下打印一列
for (int i = count + 1; i < rows - count; i++) {
rst.add(matrix[i][cols - count - 1]);
}
// count = 2 即表示最外层的 0 1 总共2层全部打印完了,正在打印第二层
// 这时总共打印了 2 * count 行或列
// 剩余行列数即为 rows - 2 * count 和 cols - 2 * count
// 从右往左打印的前提条件是未打印行列至少有两行两列
// 这时跳出当前循环,然后再执行一次从左往右打印
if (rows - 2 * count == 1 || cols - 2 * count == 1) {
break;
}
// 从右到左打印一行
for (int i = cols - count - 2; i >= count; i--) {
rst.add(matrix[rows - count - 1][i]);
}
// 从下往上打印一列
for (int i = rows - count - 2; i >= count + 1; i--) {
rst.add(matrix[i][count]);
}
// 打印完一圈,count 加 1
count++;
}
return rst;
}
}