- 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字
- 例如,如果输入如下矩阵
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
题目解读
代码
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> temp;
int row = 0;
int col = 0;
int rows = matrix.size() - 1;
int cols = matrix[0].size() -1;
while(row <= rows && col <= cols){
// 向右
if(row <= rows && col <= cols){
for(int j = col; j <= cols; j ++){
temp.push_back(matrix[row][j]);
}
row ++;
}
// 向下
if(row <= rows && col <= cols){
for(int i = row; i <= rows; i ++){
temp.push_back(matrix[i][cols]);
}
cols --;
}
// 向左
if(row <= rows && col <= cols){
for(int j = cols; j >= col; j --){
temp.push_back(matrix[rows][j]);
}
rows --;
}
// 向上
if(row <= rows && col <= cols){
for(int i = rows; i >= row; i --){
temp.push_back(matrix[i][col]);
}
col ++;
}
}
return temp;
}
void create(vector<vector<int> > &matrix){
vector<int> a;
for(int i = 1; i <= 16; i ++){
a.push_back(i);
if(i%4 == 0){
matrix.push_back(a);
a.clear();
}
}
for(int i=0; i < matrix.size(); i++){
for(int j=0; j < matrix[0].size(); j++){
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
}
};
main(){
vector<vector<int> > matrix;
Solution ss;
ss.create(matrix);
vector<int> tt = ss.printMatrix(matrix);
for(int i=0; i < tt.size(); i++){
cout<<tt[i]<<" ";
}
cout<<endl;
}
总结展望
- 不涉及数据结构和算法,仅仅是考验编程基本功,本题相当到位