题目描述
给定一个n*m的矩阵,请以顺、逆时针交替旋转的方式打印出每个元素。
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210406180030499.png)
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;
}