z
回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转90度。一开始位于矩阵左上角,方向向下。
输入格式:
输入第一行是两个不超过200的正整数m, n,表示矩阵的行和列。接下来m行每行n个整数,表示这个矩阵。
输出格式:
输出只有一行,共m*n个数,为输入矩阵回形取数得到的结果,数之间用一个空格分隔。
输入样例1:
3 3
1 2 3
4 5 6
7 8 9
输出样例1:
1 4 7 8 9 6 3 2 5
输入样例2:
3 2
1 2
3 4
5 6
输出样例2:
1 3 5 6 4 2
做法:模拟可以找到规律,每次从里向内遍历一圈,每4个方向都有规律减少,所以cot计数遍历的个数 ,当cot==row*col是break,就好了
还有不少其它solution
其中比较经典的是direct数组,但我不经常写这种,这种比这个做法个人认为更有技术含量(意思是本蒟蒻太弱了,不一定能写对)
#define ll long long
#include<bits/stdc++.h>
using namespace std;
#define fo(i,n) for(int i=1;i<=n;i++)
int row, col;
int matrix[249][249];
int main()
{
cin >> row >> col;
fo(i, row)
fo(j, col)
cin >> matrix[i][j];
int circle = 1;
int cot = 0;
while (true)
{
//down
for (int j = 1; j <= row - 2 * (circle - 1); j++)
{
cout << matrix[j+circle-1][circle] << ' ';
cot++;
}
if (cot == col * row)break;
//right
for (int j = 1; j <= col-1- 2 * (circle - 1); j++)
{
cout << matrix[row+1-circle][j+circle] << ' ';
cot++;
}
if (cot == col * row)break;
//up
for (int j = 1; j <= row - 1 - 2 * (circle - 1); j++)
{
cout << matrix[row-j-circle+1][col+1-circle] << ' ';
cot++;
}
if (cot == col * row)break;
//left
for (int j = 1; j <= col - 2 - 2 * (circle - 1); j++)
{
cout << matrix[circle][col+1-circle-j] << ' ';
cot++;
}
if (cot == col * row)break;
circle++;
}
return 0;
}
5 5
1 16 15 14 13
2 17 24 23 12
3 18 25 22 11
4 19 20 21 10
5 6 7 8 9