题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
解题思路:按照一圈一圈的打印
参考答案:
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
#include <math.h>
using namespace std;
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> my_result;
int row = matrix.size();//行
int col = matrix[0].size();//列
if (row == 0 || col == 0)
return my_result;
int i_start = 0,i_end;
int j_start = 0,j_end;
i_end = col-1;
j_end = row-1;
while (i_start <= i_end && j_start <= j_end)
{
//上面那一行(从左往右打印)
for (int i = i_start; i <= i_end; ++i) {
my_result.push_back(matrix[j_start][i]);
}
//右侧那一列(从上往下打印)
if (j_start < j_end)
{
for (int i = j_start+1; i <= j_end; ++i) {
my_result.push_back(matrix[i][i_end]);
}
}
//下面那一行(从右往左打印)
if (i_start < i_end && j_start < j_end)
{
for (int i = i_end-1; i >= i_start; --i) {
my_result.push_back(matrix[j_end][i]);
}
}
//左侧那一列(从下往上打印)
if (i_start < i_end && j_start+1 <j_end)
{
for (int i = j_end-1; i > j_start; --i) {
my_result.push_back(matrix[i][i_start]);
}
}
i_end--;
i_start++;
j_start++;
j_end--;
}
return my_result;
}
};
int main()
{
vector<int> my_m;
vector<int> result;
vector<vector<int> > my_matrix;
int count;
my_m.push_back(1);
my_m.push_back(2);
my_m.push_back(3);
my_m.push_back(4);
my_matrix.push_back(my_m);
my_m.clear();
my_m.push_back(5);
my_m.push_back(6);
my_m.push_back(7);
my_m.push_back(8);
my_matrix.push_back(my_m);
my_m.clear();
my_m.push_back(9);
my_m.push_back(10);
my_m.push_back(11);
my_m.push_back(12);
my_matrix.push_back(my_m);
my_m.clear();
my_m.push_back(13);
my_m.push_back(14);
my_m.push_back(15);
my_m.push_back(16);
my_matrix.push_back(my_m);
my_m.clear();
Solution solution;
result = solution.printMatrix(my_matrix);
// cout<<"my_matrix:"<<result[4]<<endl;
count = 0;
while (count < result.size())
{
cout<<" "<<result[count];
count++;
}
return 0;
}