试题 基础练习 回形取数
资源限制
时间限制:1.0s 内存限制:512.0MB
问题描述
回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转90度。一开始位于矩阵左上角,方向向下。
输入格式
输入第一行是两个不超过200的正整数m, n,表示矩阵的行和列。接下来m行每行n个整数,表示这个矩阵。
输出格式
输出只有一行,共mn个数,为输入矩阵回形取数得到的结果。数之间用一个空格分隔,行末不要有多余的空格。
样例输入
3 3
1 2 3
4 5 6
7 8 9
样例输出
1 4 7 8 9 6 3 2 5
样例输入
3 2
1 2
3 4
5 6
样例输出
1 3 5 6 4 2
#include<iostream>
using namespace std;
int a[200][200] = { 0 };
int b[200][200] = { 0 };
int m, n;
int min(int x, int y)
{
return x < y ? x : y;
}
int main()
{
ios::sync_with_stdio(false); //C++加速
cin.tie(0); //C++加速
cin >> m >> n;
int posy = m; //列的末位
int posx = n; //行的末位
int posy0 = 1; //列的首位
int posx0 = 1; //行的首位
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> a[i][j]; //输入数据
}
}
int r = (min(m, n) + 1) / 2;//循环次数
for (int k = 1; k <= r; k++)
{
if (k == r && (m % 2 == 1))//如果行数为奇数且为最后一圈循环
{
int i ;
for (i = posy0; i <= posy; i++)
{
if (i == 1 && k == 1)
{
cout << a[1][1] << " ";//防止出现1行多列或1列多行的情况
}
else
{
cout << a[i][posx0] << " ";
}
}
posx0++;
while (posx0 <= posx )
{
for (int j = posy; j >= posy0; j--)
{
cout << a[j][posx0] << " ";
}
posx0++;
}
}
else if (k == r && (n % 2 == 1))//如果列数为奇数且为最后一圈循环
{
int i ;
for (i = posx0; i <= posx; i++)
{
if (i == 1 && k == 1)
{
cout << a[1][1] << " ";
}
else
{
cout << a[posy0][i] << " ";
}
}
posy0++;
while (posy0 <= posy )
{
for (int j = posx; j >= posx0; j--)
{
cout << a[posy0][j] << " ";
}
posy0++;
}
}
else
{
for (int i = posy0; i <= posy; i++)//第一次小循环
{
cout << a[i][posx0] << " ";
}
posx0++;
for (int i = posx0; i <= posx; i++)//第二次小循环
{
cout << a[posy][i] << " ";
}
posy--;
for (int i = posy; i >= posy0; i--)//第三次小循环
{
cout << a[i][posx] << " ";
}
posx--;
for (int i = posx; i >= posx0; i--)//第四次小循环
{
cout << a[posy0][i] << " ";
}
posy0++;
}
}
return 0;
}