题目
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
思路
- 使用暴力解法
- 按照顺时针顺序循环
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
return res;
}
int rowBegin = 0;
int rowEnd = matrix.length - 1;
int colBegin = 0;
int colEnd = matrix[0].length - 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
for (int i = colBegin; i <= colEnd; i++) {//右
res.add(matrix[rowBegin][i]);
}
rowBegin++;//1
for (int i = rowBegin; i <= rowEnd; i++) {//下
res.add(matrix[i][colEnd]);
}
colEnd--;//1
if (rowBegin <= rowEnd) {//判断是否有多次
for (int i = colEnd; i >= colBegin; i--) {
res.add(matrix[rowEnd][i]);//左
}
}
rowEnd--;
if (colBegin <= colEnd) {
for (int i = rowEnd; i >= rowBegin; i--) {
res.add(matrix[i][colBegin]);//上
}
}
colBegin++;
}
return res;
}
}