旋转的矩阵-c++

13 篇文章 2 订阅
12 篇文章 4 订阅

旋转的矩阵-数据结构

题目描述
给定一个n*m的矩阵,请以顺、逆时针交替旋转的方式打印出每个元素。

Input Format

第一行n m; 0<n,m<100

后n行,每行m个整数。

Output Format
n*m个矩阵元素,空格隔开。

Example
Input
4 4

1 2 3 4

12 13 16 5

11 14 15 6

10 9 8 7

Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Input
3 4

1 2 3 4

10 11 12 5

9 8 7 6

Output

1 2 3 4 5 6 7 8 9 10 11 12

#include<iostream>
#include<vector>
using namespace std;
int main()
{
    int m, n;
    while(cin >> m >> n)
    {
        vector<vector<int>> res(m, vector<int>(n));
        for(int i = 0; i < m; i++)
        {
        	for (int j = 0; j < n; j++) cin >> res[i][j];
		}

        int row = res.size();
        int col = res[0].size();
        int left = 0, right = col-1, top = 0, bottom = row-1;
        vector<int> s;
        while(left <= right && top <= bottom) 
        {
            /*顺时针*/
            for(int i = left; i <= right; i++) s.push_back(res[top][i]);

            for(int i = top + 1; i <= bottom; i++) s.push_back(res[i][right]); 
			   
            if(top != bottom)
            {
                 for(int i = right - 1; i >= left; i--) s.push_back(res[bottom][i]);    
            }

            if(left != right)
            {
                 for(int i = bottom - 1;i >= top + 1 ; i--) s.push_back(res[i][left]);    
            }
            left++, top++, right--, bottom--;
            /*当矩阵较大,能够绕完顺时针后再逆时针绕圈时,
            以下为逆时针录入情况*/
            if(left < right && top < bottom)
            {
				for(int i = top; i <= bottom ; i++) s.push_back(res[i][left]);
	            
	            for(int i = left + 1; i <= right ; i++) s.push_back(res[right-1][i]);
	            
	            if(left != right)
	            {
	            	for(int i = bottom - 1; i >= top; i--) s.push_back(res[i][right]);
				}
				if(top != bottom)
				{
					for(int i = right - 1; i >= left + 1; i--) s.push_back(res[top][i]);
				}
				left++, top++, right--, bottom--;
			}
        }
        for(int i = 0; i < s.size(); i++)
        {
            if (i == s.size() - 1)
                cout << s[i] << endl;
            else
                cout << s[i] << ' ';
        }
        
    }
    return 0;
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值