给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。 示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
按照顺时针的顺序访问二维数组,通过while循环,跳出条件就是访问的数量和二维数组里所有元素的总和一致num <= toal
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int l = 0, r = matrix[0].length - 1, t = 0, b = matrix.length - 1;
List<Integer> list = new ArrayList<>();
int toal = matrix.length * matrix[0].length;
int num = 1;
while (num <= toal) {
for (int i = l; i <= r && num <= toal ; i++) { //从左到右
list.add(matrix[t][i]);
num++;
}
t++;
for (int i = t; i <= b && num <= toal ; i++) { //从上到下
list.add(matrix[i][r]);
num++;
}
r--;
for (int i = r; i >= l && num <= toal ; i--) { //从右到左
list.add(matrix[b][i]);
num++;
}
b--;
for (int i = b; i >= t && num <= toal ; i--) { //从下到上
list.add(matrix[i][l]);
num++;
}
l++;
}
return list;
}
}