输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个元素。
例如:
输入矩阵:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出:[1,2,3,6,9,8,7,4,5]
这是一个非常经典的二维数组模拟题。
思路总结:
我们可以把矩阵想象成一圈一圈的“洋葱”,从最外层开始,顺时针打印每一圈的四条边:
每打印完一层就缩小一圈范围,直到所有元素都被访问。
#include
using namespace std;
class Solution {
public:
vector< int > spiralOrder( vector< vector< int > >& matrix )
{
vector< int > result;
if ( matrix.empty() )
return result;
int rows = matrix.size();
int cols = matrix[ 0 ].size();
// 定义当前圈的四个边界
int top = 0, bottom = rows - 1;
int left = 0, right = cols - 1;
while ( top <= bottom && left <= right )
{
// 1. 从左到右
for ( int i = left; i <= right; ++i )
{
result.push_back( matrix[ top ][ i ] );
}
top++; // 上边界下移
// 2. 从上到下
for ( int i = top; i <= bottom; ++i )
{
result.push_back( matrix[ i ][ right ] );
}
right--; // 右边界左移
// 注意:可能只剩一行或一列的情况,需要判断是否还存在下边和左边
if ( top <= bottom )
{
// 3. 从右到左
for ( int i = right; i >= left; --i )
{
result.push_back( matrix[ bottom ]`在这里插入代码片`[ i ] );
}
bottom--; // 下边界上移
}
if ( left <= right )
{
// 4. 从下到上
for ( int i = bottom; i >= top; --i )
{
result.push_back( matrix[ i ][ left ] );
}
left++; // 左边界右移
}
}
return result;
}
};
#include
int main()
{
vector< vector< int > > matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Solution sol;
vector< int > result = sol.spiralOrder( matrix );
cout << "顺时针打印结果:" << endl;
for ( int num : result )
{
cout << num << " ";
}
return 0;
}
顺时针打印结果:
1 2 3 6 9 8 7 4 5