外观
矩阵螺旋遍历
⭐ 题目日期:
百度 - 2024/10/20
🌳 题目描述:
给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
🧗难度系数:
⭐️ ⭐️ ⭐
📝思路分析:
4个方向遍历,
1-->2-->3
向右:(RowBegin, ColumnBegin), (RowBegin, ColumnBegin + 1), ... (RowBegin, ColumnEnd)
RowBegin 行访问完成,RowBegin++;
6-->9
向下: (RowBegin, ColumnEnd), (RowBegin + 1, ColumnEnd), ... (RowEnd, ColumnEnd)
ColumnEnd 列访问完成,ColumnEnd--;
8-->7
向左: (RowEnd, ColumnEnd), (RowEnd, Column - 1), ... (RowEnd, ColumnBegin)
RowEnd 行访问完成,RowEnd--;
4
向上:(RowEnd, ColumnBegin), (RowEnd - 1, ColumnBegin), ... (RowBegin, ColumnBegin)
ColumnBeign 列访问完成,ColumnBegin++;
重复以上步骤,直到所有元素遍历完
💻代码:
Java
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix.length == 0) {
return result;
}
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++) {
result.add(matrix[rowBegin][i]);
}
rowBegin++;
for (int i = rowBegin; i <= rowEnd; i++) {
result.add(matrix[i][colEnd]);
}
colEnd--;
if (rowBegin <= rowEnd) {
for (int i = colEnd; i >= colBegin; i--) {
result.add(matrix[rowEnd][i]);
}
rowEnd--;
}
if (colBegin <= colEnd) {
for (int i = rowEnd; i >= rowBegin; i--) {
result.add(matrix[i][colBegin]);
}
colBegin++;
}
}
return result;
}
🚵🏻复杂度分析:
时间复杂度:O(m * n), m 行 n 列的二维数组
空间复杂度:O(1)