#include <iostream>
#include <vector>
using namespace std;
vector<int> printMatrix(vector<vector<int> > matrix) {
int row = matrix.size();
int col = matrix[0].size();
vector<int> res;
// 输入的二维数组非法,返回空的数组
if (row == 0 || col == 0) return res;
// 定义四个关键变量,表示左上和右下的打印范围
int left = 0, top = 0, right = col - 1, bottom = row - 1;
while (left <= right && top <= bottom)
{
// top to bottom
for (int i = top ; i <= bottom; ++i) res.push_back(matrix[i][left]);
// left to right
for (int i = left+1; i <= right; ++i) res.push_back(matrix[bottom][i]);
// bottom to top
if (left != right)
for (int i = bottom -1; i > top; --i) res.push_back(matrix[i][right]);
// right to left
if (top != bottom)
for (int i = right ; i > left; --i) res.push_back(matrix[top][i]);
left++,top++,right--,bottom--;
}
return res;
}
int main()
{
vector<vector <int> > matrix={{1,2,3},{4,5,6},{7,8,9}};
for (vector<vector<int>>::iterator it = matrix.begin(); it != matrix.end(); ++it)
for (int i = 0; i < (*it).size(); ++i)
cout << (*it)[i] << " " ;
vector<int> result=printMatrix(matrix);
for (vector<int>::iterator it = result.begin(); it != result.end(); ++it)
cout << (*it) << " " ;
return 0;
}
矩阵逆序打印
最新推荐文章于 2023-09-19 23:51:47 发布