leetcode链接
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
示例 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]
每次按照顺时针螺旋顺序处理矩阵的一条边时通过矩阵当前的上下左右边界定位要处理的元素位置。每处理完一条边更新边界。当左边界大于右边界或者上边界大于下边界时处理结束。
class Solution {
/*
时间复杂度:O(m * n)
空间复杂度:O(m * n)
*/
public List<Integer> spiralOrder(int[][] matrix) {
//注意:当矩阵为空时需单独处理,否则在初始化边界时会出错
if (matrix.length == 0)
return new ArrayList<Integer>();
//矩阵的上、下、左、右边界
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
//存储结果
//注意:此处必须为Integer,否则后续无法将该数组转换为List
Integer[] res = new Integer [(bottom + 1) * (right + 1)];
int count = 0;
//按照螺旋轨迹依次取出元素
while (true) {
//从左到右
for (int i = left; i <= right; i++) {
res[count++] = matrix[top][i];
}
//更新上边界
if (++top > bottom) break;
//从上到下
for (int i = top; i <= bottom; i++) {
res[count++] = matrix[i][right];
}
//更新右边界
if (--right < left) break;
//从右到左
for (int i = right; i >= left; i--) {
res[count++] = matrix[bottom][i];
}
//更新下边界
if (top > --bottom) break;
//从下到上
for (int i = bottom; i >= top; i--) {
res[count++] = matrix[i][left];
}
//更新左边界
if (right < ++left) break;
}
return Arrays.asList(res);
}
}
left) break;
}
return Arrays.asList(res);
}
}
####