C++代码如下:
# include <iostream>
# include <vector>
using namespace std;
int main()
{
int m, n;
cin >> m >> n;
int a[200][200];
for (int i = 0; i < m; i++) //二维数组输入
for (int j = 0; j < n; j++)
cin >> a[i][j];
int num = 0;
int i = 0, j = 0;
int flag = 1; //flag代表方向
int aflag=m, bflag=n, cflag=0, dflag=1; //记录每一个方向的最后一个位置
vector<int> b; //向量来记录数组输出顺序
while (num != m * n)
{
b.push_back(a[i][j]);
if (flag == 1)
{
if (i < aflag-1)
i++;
else
{
flag = 2;
j++;
aflag--;
}
num++;
continue;
}
if (flag == 2)
{
if (j< bflag - 1)
j++;
else
{
flag = 3;
i--;
bflag--;
}
num++;
continue;
}
if (flag == 3)
{
if (i >cflag)
i--;
else
{
flag = 4;
j--;
cflag++;
}
num++;
continue;
}
if (flag == 4)
{
if (j >dflag)
j--;
else
{
flag = 1;
i++;
dflag++;
}
num++;
continue;
}
}
for (int i = 0; i < b.size()-1; i++)
cout << b[i]<<" ";
cout << b[b.size() - 1];
return 0;
}
|