Problem Description
现在有一个二维的字符数组,要求你从左上角开始,顺时针前进,按照螺旋形输出经过的字符,每个位置只会经过一次,直到走完整个矩阵,例如:
字符矩阵如下:
abc
def
ghi
从左上角a开始,按照顺时针,经过a b c f i h g d 然后向右转 到 e
于是输出为:abcfihgde
字符矩阵如下:
abc
def
ghi
从左上角a开始,按照顺时针,经过a b c f i h g d 然后向右转 到 e
于是输出为:abcfihgde
Input
输入的第一行为一个整数T,代表有T组样例
对于每一组样例,第一行为n,代表字符矩阵大小为n*n
接下来n行,每一行输入n个字符,表示字符矩阵
0<n<=10 ,0<T<20 保证字符矩阵中全是小写字母
对于每一组样例,第一行为n,代表字符矩阵大小为n*n
接下来n行,每一行输入n个字符,表示字符矩阵
0<n<=10 ,0<T<20 保证字符矩阵中全是小写字母
Output
对于每一组样例单独输出一行,表示经过的字符
Sample Input
1 4 abcd lmne kpof jihg
Sample Output
abcdefghijklmnop
#include<iostream>
#include<string>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
char **a; //new二维数组
a = new char *[n];
for (int i = 0; i < n; i++)
a[i] = new char[n];
for (int i = 0; i < n; i++) //输入
for (int j = 0; j < n; j++)
cin >> a[i][j];
int x1 = 0, y1 = 0; //初始化拐点
int x2 = 0, y2 = n - 1;
int x3 = n - 1, y3 = n - 1;
int x4 = n, y4 = -1;
int x=0, y=0;
lable:x4 -= 1, y4 += 1;
for (y = y1; y <= y2; y++)
cout << a[x1][y];
if (y1 == y2) goto end;
x1 += 1, y1 += 1;
for (x = x2 + 1; x <= x3; x++)
cout << a[x][y2];
if (x2 == x3) goto end;
x2 += 1, y2 -= 1;
for (y = y3 - 1; y >= y4; y--)
cout << a[x3][y];
if (y3 == y4)goto end;
x3 -= 1, y3 -= 1;
for (x = x4 - 1; x >= x1; x--)
cout << a[x][y4];
if (x4 == x1) goto end;
else goto lable;
end:cout << endl;
for (int i = 0; i < n; i++)
delete[] a[i];
delete[] a;
}
}
使用了goto语句,可能有点逻辑混乱,期待高手指正。