旋转的矩阵

旋转的矩阵

题目描述

给定一个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

样例输入输出
样例1
输入:
1 3
3 4 1
输出:
3 4 1
样例2
输入:
4 4
1 2 3 4
12 13 16 5
11 14 15 6
10 9 8 7
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
样例3
输入:
3 1
6
5
7
输出:
6 5 7

//
// Created by w_xing on 2021/4/6.
//

#include <iostream>
using namespace std;

int main() {
    int n, m;
    cin >> n >> m;
    int num = n*m;
    int *matrix = new int [num];
    for (int i=0; i<num; i++) {
        cin >> matrix[i];
    }
    // 数组下标映射关系 int arr[i][j] = int arr[i*m + j]
    int count = 0;
    int i, j;
    int left = 0, right = m-1, top = 0, bottom = n-1; //定位
    while (count<num) {
        //顺时针输出
        if (left < right && top < bottom) {
           for (i=top, j=left; j<right; j++) { //从左到右
               cout << matrix[i*m + j] << " ";
               count++;
           }
            for (j=right; i<bottom; i++) { //从上到下
                cout << matrix[i*m + j] << " ";
                count++;
            }
            for (i=bottom; j>left; j--) { //从右到左
                cout << matrix[i*m + j] << " ";
                count++;
            }
            for (j=left; i>top; i--) { //从下到上
                cout << matrix[i*m + j] << " ";
                count++;
            }
           left++; right--; top++; bottom--;
        }
        //逆时针输出
        if (left < right && top < bottom) {
            //逆时针
            for (i=top, j=left; i<bottom; i++) { //从上到下
                cout << matrix[i*m + j] << " ";
                count++;
            }
            for (i=bottom; j<right; j++) { //从左到右
                cout << matrix[i*m + j] << " ";
                count++;
            }
            for (j=right; i>top; i--) { //从下到上
                cout << matrix[i*m + j] << " ";
                count++;
            }
            for (i=top; j>left; j--) { //从右到左
                cout << matrix[i*m + j] << " ";
                count++;
            }
            left++; right--; top++; bottom--;
        }
        if (left == right) {
            for (i=top,j=left; i<=bottom; i++) {
                cout << matrix[i*m + j] << " ";
                count++;
            }
        }
        if (top == bottom) {
            for (i=top,j=left; j<=right; j++) {
                cout << matrix[i*m + j] << " ";
                count++;
            }
        }
    }
    delete[] matrix;
    return 0;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值