Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。 Example 1:
Input
:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output
: [1,2,3,6,9,8,7,4,5]
Example 2:
Input
:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output
: [1,2,3,4,8,12,11,10,9,5,6,7]
思路
进行模拟,核心算法在于如何按→ ↓ ← ↑的顺时针顺序遍历数组,具体做法就是利用directions[4][2]数组,4表示上下左右4个方向,2表示行和列。 处理边界 利用nextrow ,nextcol来处理边界情况,超出边界时就改变遍历的方向。 利用visited数组储存已经遍历过的地方,下一次遇到时就改变方向,保证该 顺时针遍历 从外到内层层遍历。
C++
class Solution {
private:
int directions
[4][2] = {{0, 1},{1, 0},{0, -1},{-1, 0}};
public:
vector
<int> spiralOrder(vector
<vector
<int>>& matrix
) {
if(matrix
.size() == 0) return {};
int rows
= matrix
.size(), cols
= matrix
[0].size();
int total
= rows
* cols
;
int row
= 0, col
= 0;
int idx
= 0;
vector
<vector
<bool>> visited(rows
, vector
<bool>(cols
));
vector
<int> order(total
);
for(int i
= 0; i
< total
; i
++){
visited
[row
][col
] = true;
order
[i
] = matrix
[row
][col
];
int nextrow
= row
+ directions
[idx
][0];
int nextcol
= col
+ directions
[idx
][1];
if(nextrow
< 0 || nextcol
< 0 || nextrow
>= rows
|| nextcol
>= cols
|| visited
[nextrow
][nextcol
]){
idx
= (idx
+ 1) % 4;
}
row
+= directions
[idx
][0];
col
+= directions
[idx
][1];
}
return order
;
}
};