算法题(7)顺时针打印矩阵

算法题(7)顺时针打印矩阵

每天两道算法题

题目

  • 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
  • 例如,如果输入如下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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值