题目信息
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
matrix3_4.jpg
输入: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]
解题思路
- 暴力破解:
- 无效操作分析:
- 优化方法:
- 考虑边界
- 编码实现
代码
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
// 判断矩阵非空
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
// 获取循环数量
int rows = matrix.length, columns = matrix[0].length;
int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom){
// 上
for (int column = left; column <= right; column++) {
result.add(matrix[top][column]);
}
// 右
for (int row = top + 1; row <= bottom; row++) {
result.add(matrix[row][right]);
}
if (left < right && top < bottom) {
// 下
for (int column = right - 1; column > left; column--) {
result.add(matrix[bottom][column]);
}
// 左
for (int row = bottom; row > top; row--) {
result.add(matrix[row][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return result;
}
}
题目来源:力扣(LeetCode)
题目链接:https://leetcode-cn.com/problems/spiral-matrix
商业转载请联系官方授权,非商业转载请注明出处。