问题描述
回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转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<stdio.h>
#include<iostream>
#include<algorithm>
int num[201][201];
using namespace std;
int main(){
int m,n;
cin>>m>>n;
for(int i=0;i<=m+1;i++){//输入
for(int j=0;j<=n+1;j++){
num[i][j]=-1;
}
}
for(int i=1;i<=m;i++){//输入
for(int j=1;j<=n;j++){
cin>>num[i][j];
}
}
int x=0,y=0;
int count=0;
while(1){
x+=1;y+=1;//下转
while(num[x][y]!=-1){//下
cout<<num[x][y]<<" ";
num[x][y]=-1;
count++;
x++;
}
if(count>=m*n)break;
x-=1;y+=1;//右转
while(num[x][y]!=-1){//右
cout<<num[x][y]<<" ";
num[x][y]=-1;
count++;
y++;
}
if(count>=m*n)break;
x-=1;y-=1;//上转
while(num[x][y]!=-1){//上
cout<<num[x][y]<<" ";
num[x][y]=-1;
count++;
x--;
}
if(count>=m*n)break;
x+=1;y-=1;//左转
while(num[x][y]!=-1){//左
cout<<num[x][y]<<" ";
num[x][y]=-1;
count++;
y--;
}
if(count>=m*n)break;
}
return 0;
}