#include<iostream>
using namespace std;
//给矩阵输出顺序设定为右下左上四个方向即可
//set the lower right and upper left direction for the matrix output
typedef struct
{
int x;
int y;
}direction;
void Output(int a[][4],direction dir[] )
{
int index = 0;//方位
int i = 0;
int j = 0;
//设定墙(set wall)
int bottom_X = 0;
int top_X = 4;
int bottom_Y = 0;
int top_Y = 4;
//当所有墙重合是结束
while (bottom_Y != top_Y&&bottom_X!=top_X)
{
while (index < 4)
{
if (i >= bottom_Y && i < top_Y && j >= bottom_X && j < top_X)
{
cout << a[i][j] << " ";
//实现坐标的移动(realize the movement of coordinates)
i += dir[index].y;//i对应y坐标(i corresponds to y coordinate)
j += dir[index].x;//j对应x坐标(j corresponds to x coordinate)
}
//注意当第一次跳出的时候j=4。第三第四等等情况已经越界无法第二次进入输出,在switch回退到各个合适的顶部或底部位置
else
{
switch (index)
{
//每走完一个方位就要有一面墙的位置增加或减少
//after each direction ,the position of one wall wil increase or decrease
case 0:++bottom_Y; //遍历完一层上底部的墙向下移
++i;//墙下移了,i也要下移,不然i无法>=bottom_Y无法继续下一步循环
--j;//跳出循环时j=4,要回退一步
break;
case 1:--top_X; --i; --j;
break;
case 2:--top_Y; ++j; --i;
break;
case 3:++bottom_X; ++i; ++j;
break;
}
++index;//走到尽头换个方向(go to the end and change direction)
}
}
index = 0;
}
}
int main()
{
int a[4][4] =
{
1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16
};
direction dir[4] =
{
1,0,//turn right
0,1,//go down
-1,0,//turn left
0,-1//do up
};
Output(a, dir);
}
|