c++面试题(14)------顺时针打印矩阵
- 操作系统:ubuntu22.04
- IDE:Visual Studio Code
- 编程语言:C++11
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个元素。
例如:
输入矩阵:
[[ 1, 2, 3 ],[ 4, 5, 6 ],[ 7, 8, 9 ]
]输出:[1,2,3,6,9,8,7,4,5]
解法思路:模拟边界遍历(按圈打印)
这是一个非常经典的二维数组模拟题。
🧠 思路总结:
我们可以把矩阵想象成一圈一圈的“洋葱”,从最外层开始,顺时针打印每一圈的四条边:
- 从左到右 打印上边;
- 从上到下 打印右边;
- 从右到左 打印下边;
- 从下到上 打印左边;
每打印完一层就缩小一圈范围,直到所有元素都被访问。
实现代码
#include <vector>
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 <iostream>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