题解:B4226 [常州市程序设计小能手 2024] 密码
题目传送门
Solution
这题我的思路是,首先用
Code
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=510;
int n,i,j,d;
char a[N][N];
char ch1[N][N];
char ch2[N][N];
const int di[4]={0,1,0,-1};
const int dj[4]={1,0,-1,0};
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cin>>a[i][j];
//蛇形遍历生成中间形式 ch1
i=1;j=1;d=1;
for(int x=1;x<=n;x++){
for(int y=1;y<=n;y++){
ch1[x][y]=a[i][j];
i-=d;j+=d;
if(j>n){
j=n;
i+=2;
d=-d;
}
else if(i>n){
i=n;
j+=2;
d=-d;
}
else if(i<1){
i=1;
d=-d;
}
else if(j<1){
j=1;
d=-d;
}
}
}
//螺旋遍历填入最终形式 ch2
d=0;//0:右,1:下,2:左,3:上
int cnt=1;
int left=1,right=n,up=1,down=n;
while(left<=right&&up<=down){
if(d==0){
for(int i=left;i<=right;i++){
ch2[up][i]=ch1[(cnt-1)/n+1][(cnt-1)%n+1];
cnt++;
}
up++;
}
else if(d==1){
for(int i=up;i<=down;i++){
ch2[i][right]=ch1[(cnt-1)/n+1][(cnt-1)%n+1];
cnt++;
}
right--;
}
else if(d==2){
for(int i=right;i>=left;i--){
ch2[down][i]=ch1[(cnt-1)/n+1][(cnt-1)%n+1];
cnt++;
}
down--;
}
else if(d==3){
for(int i=down;i>=up;i--){
ch2[i][left]=ch1[(cnt-1)/n+1][(cnt-1)%n+1];
cnt++;
}
left++;
}
d=(d+1)%4;
}
//输出最终形式 ch2
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)
cout<<ch2[i][j];
cout<<"\n";
}
return 0;
}