螺旋打印矩阵(顺时针)——C++

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 

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 <algorithm>
#include <vector>
using namespace std;
 
vector<int> printMatrix(vector<vector<int> > matrix)
{
    vector<int> pMR;
    //初始化位置
    int left=0,right=matrix.front().size()-1;
    int top=0,bottom=matrix.size()-1;
    //测试打印
    cout<<left<<right<<top<<bottom<<endl;
    while(left<=right && top<=bottom)
    {
        //设置标记,记录转圈的位置
        int l=left,r=right-1,t=top+1,b=bottom-1;
        //从左到右
        while(l<=right)
            pMR.push_back(matrix[top][l++]);
        //从上到下
        while(t<=bottom)
            pMR.push_back(matrix[t++][right]);
        //从右到左
        while(top<bottom&&r>=left&&left<right)
            pMR.push_back(matrix[bottom][r--]);
        //从下到上
        while(top+1<bottom&&b>=top+1&&left<right)
            pMR.push_back(matrix[b--][left]);
        //更新位置
        left++;
        right--;
        top++;
        bottom--;
    }
    return pMR;
}
 
int main()
{
    vector<vector<int> > matrix;
    //测试数据
    for(int i=0,j=1; i<4; i++)
    {
        vector<int> vect;
        for(int k=0; k<4; k++,j++)
        {
            vect.push_back(j);
            cout<<j<<" ";
        }
        cout<<endl;
        matrix.push_back(vect);
    }
    vector<int> temp = printMatrix(matrix);
    for(int i = 0; i < temp.size(); i++)
        cout << temp[i] <<" ";
    cout << endl;

    return 0;
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Star星屹程序设计

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值