问题描述
回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转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
代码
#include<stdio.h>
#include<iostream>
using namespace std;
struct DIR{ //用于确定读取方向
int row,col;
}dir[4] = {{1,0},{0,1},{-1,0},{0,-1}}; // 下 右 上 左
int main(){
int num[205][205] = {0};
int m,n;
int d = 0,row = 0,col = 0,row1,col1;
int k;
int i,j;
cin>>m>>n;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
scanf("%d",&num[i][j]);
}
}
k = m*n;
while(k--){
printf("%d ",num[row][col]);
num[row][col] = -1; //将读完的数置-1
row1 = dir[d].row + row; // 保存下一个数的读取方向
col1 = dir[d].col + col; // 保存下一个数的读取方向
if(row1 < 0 || row1 >= m || col1 < 0 || col1 >= n || num[row1][col1] == -1){ //判断该方向是否可行
d = (d+1)%4;
row1 = dir[d].row + row;
col1 = dir[d].col + col;
}
row = row1; // 将正确的读取方向保存
col = col1; // 将正确的读取方向保存
}
return 0;
}