题目
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
思路
模拟题:
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<>();
int x = 0, y = 0, m = matrix.length - 1, n = matrix[0].length - 1;
while(x <= n && y <= m){
//从左到右,遍历顶部第y行
for(int i = x; i <= n; ++i){
ans.add(matrix[y][i]);
}
//从下面一行继续开始遍历
y++;
//从上到下,遍历右边第n列
for(int i = y; i <= m; i++){
ans.add(matrix[i][n]);
}
//从左边一列继续开始遍历
n--;
//从右到左,遍历底部第m行
for(int i = n; i >= x && m >= y; --i){//m >= y是为了避免重复遍历行,顶部已经遍历的行就不再遍历
ans.add(matrix[m][i]);
}
//从上面一行继续开始遍历
m--;
//从下到上
for(int i = m; i >= y && x <= n; --i){// x <= n是为了避免重复遍历列,右边已经遍历的列就不再遍历
ans.add(matrix[i][x]);
}
x++;
}
return ans;
}
}