题目: https://atcoder.jp/contests/abc335/tasks/abc335_d
思想: 令 flag = 0,1,2,3 分别代表四个方向右,下,左,上,然后判断下一步是否超过边界或者被填充过,如果是,就换方向,最后输出。
代码:
// Problem: D - Loong and Takahashi
// Contest: AtCoder - AtCoder Beginner Contest 335 (Sponsored by Mynavi)
// URL: https://atcoder.jp/contests/abc335/tasks/abc335_d
// Memory Limit: 1024 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 101;
const int inf = 0x3f3f3f3f;
int n;
int g[N][N];
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin>>n;
int p=1;
int flag=0;
int x=1,y=0;
while(p<=n*n-1){
if(flag==0) y++;
else if(flag==1) x++;
else if(flag==2) y--;
else if(flag==3) x--;
g[x][y]=p;
p++;
int a=x,b=y;
if(flag==0) b++;
else if(flag==1) a++;
else if(flag==2) b--;
else if(flag==3) a--;
if(a>n||b>n||b<=0||a<=0||g[a][b]){
flag++; //边界或者是否填充过
}
flag%=4;
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(g[i][j]){
cout<<g[i][j]<<' ';
}
else cout<<'T'<<' ';
}
cout<<"\n";
}
cout<<"\n";
return 0;
}