這題我覺得根本是在找bug花了一大堆時間...(換行和空格就夠麻煩了...)
我的解法是開個大陣列,從中間開始填,填完後再填空白。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<string>
#include<sstream>
using namespace std;
char map[1000][1000];
char s[10000];
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%s",s);
memset(map,0,sizeof(map));
int len=strlen(s),x=500,y=500,v=4;//1 right , 2 left , 3 up , 4 down
for(int i=0;i<len;i++){
map[y][x]=s[i];
if(v==1){
if(map[y-1][x]==0)v=3,y--;
else x++;
}
else if(v==2){
if(map[y+1][x]==0)v=4,y++;
else x--;
}
else if(v==3){
if(map[y][x-1]==0)v=2,x--;
else y--;
}
else if(v==4){
if(map[y][x+1]==0)v=1,x++;
else y++;
}
}
int sx=500,sy=500,ex=500,ey=500;
for(int i=0;i<1000;i++){
for(int j=0;j<1000;j++){
if(map[i][j]!=0){
if(i<sx){sx=i;}
if(i>ex){ex=i;}
if(j<sy){sy=j;}
if(j>ey){ey=j;}
}
}
}
for(int i=sx;i<=ex;i++){
for(int j=sy;j<ey;j++){
if(map[i][j]=='\0'){
map[i][j]=' ';
}
else break;
}
}
for(int i=sx;i<=ex;i++){
printf("%s\n",map[i]+sy);
}
puts("");
}
return 0;
}