给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> order = new ArrayList<>();
int rows = matrix.length; // 行数
int 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++) {
order.add(matrix[top][column]);
}
for (int row = top + 1; row <= bottom; row++) {
order.add(matrix[row][right]);
}
if (left < right && top < bottom) { // 必须加判断,否则单行列会重复打印
for (int column = right - 1; column > left; column--) {
order.add(matrix[bottom][column]);
}
for (int row = bottom; row > top; row--) {
order.add(matrix[row][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return order;
}
该博客介绍了如何实现一个算法,以顺时针螺旋顺序返回给定矩阵的所有元素。通过维护四个边界,逐步缩小矩阵范围,依次遍历每一层的元素,实现了螺旋遍历的过程。
936

被折叠的 条评论
为什么被折叠?



