剑指offer19:按照从外向里以顺时针的顺序依次打印出每一个数字,4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

时间:2022-12-22 08:14:59

1 题目描述

  输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

2 思路和方法

  直接定义一个矩形,在矩形的四条边取值,程序大大简化。

3 核心代码

 class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int>vec;
int row = matrix.size();
int column = matrix[].size();
int left = , right = column, up = , bottom = row;
while((up < bottom) && (left < right))
{
for(int i = left; i < right; i++) vec.push_back(matrix[up][i]);
for(int i = up+; i < bottom; i++) vec.push_back(matrix[i][right-]);
for(int i = right--; ((bottom-)!=up)&&(i >=left); i--) vec.push_back(matrix[bottom-][i]);
for(int i = bottom--; ((right-)!=left)&&(i >left); i--) vec.push_back(matrix[i][left]);
up++;left++; right--; bottom--;
}
return vec;
}
};

4 完整代码

 #include<iostream>
#include<vector> using namespace std; //直接定义一个矩形,在矩形的四条边取值,程序大大简化
class Solution{
public:
vector<int>printMatrix(vector<vector<int>> matrix) {
vector<int>vec;
int row = matrix.size();
int column = matrix[].size();
int left = , right = column, up = , bottom = row;
while ((up < bottom) && (left < right))
{
for (int i = left; i < right; i++) vec.push_back(matrix[up][i]);
for (int i = up + ; i < bottom; i++) vec.push_back(matrix[i][right - ]);
for (int i = right - - ; ((bottom - ) != up) && (i >= left); i--) vec.push_back(matrix[bottom - ][i]);
for (int i = bottom - - ; ((right - ) != left) && (i >left); i--) vec.push_back(matrix[i][left]);
up++; left++; right--; bottom--;
}
return vec;
}
}; int main() {
Solution a;
vector<vector<int>> matrix = { { , , , , }, { , , , , }, { , , , , } };//矩阵初始化
vector<int> m = a.printMatrix(matrix);
for (auto i : m)//依次打印返回矩阵的值
cout << i << " ";
cout << endl; return ; }

参考资料

https://blog.csdn.net/hangsyt108/article/details/80949337