每天两道算法题
题目
- 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
- 例如,如果输入如下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>
using namespace std;
vector<int> sortMatrix(vector<vector<int>> mat);
int main( void )
{
vector<vector<int>> mat;
vector<int> vec;
for( int i=0; i<5; ++i ) {
vec.clear();
for( int j=0; j<5;++j ) {
vec.push_back( i*5+j+1 );
}
mat.push_back( vec );
}
vector<int> m( sortMatrix( mat ) );
for( int i=0; i<mat.size(); ++i ) {
for( vector<int>::iterator pos=mat[i].begin(); pos!=mat[i].end(); ++pos ) {
cout << *pos << " ";
}
cout << endl;
}
for( vector<int>::iterator pos=m.begin(); pos!=m.end(); ++pos ) {
cout << *pos << " ";
}
cout << endl;
return 0;
}
vector<int> sortMatrix(vector<vector<int>> mat)
{
// 在这插入代码
}
$ ./a.out
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6 7 8 9 14 19 18 17 12 13
C++ 代码
vector<int> sortMatrix(vector<vector<int>> mat)
{
vector<int> res;
int row = mat.size();
int col = mat[0].size();
int cir = row<col ? 1+(row-1)/2 : 1+(col-1)/2;
for( int i=0; i<cir; ++i ) {
//从左向右打印
for( int j=i; j<col-i; ++j )
res.push_back( mat[i][j] );
//从上往下的每一列数据
for( int j=i+1; j<row-i; ++j )
res.push_back( mat[j][col-1-i] );
//判断是否会重复打印(从右向左的每行数据)
for( int j=col-i-2; (j>=i)&&(row-i-1!=i); --j )
res.push_back( mat[row-i-1][j] );
//判断是否会重复打印(从下往上的每一列数据)
for( int j=row-i-2; (j>i)&&(col-i-1!=i); --j )
res.push_back( mat[j][i] );
}
return res;
}