AcWing 3208. Z字形扫描(dfs)
原题链接
简单
作者:
smile_922
,
2023-11-16 20:33:17
,
所有人可见
,
阅读 69
看各位佬都用循环写,我来水个dfs
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510;
int g[N][N];
int dx[]={-1,1},dy[]={1,-1};//方向
int n;
void dfs(int a,int b,int c){
if(a<=0||a>n||b<=0||b>n)return;//边界处理
cout<<g[a][b]<<' ';
int x = a+dx[c],y=b+dy[c];
if(x==n+1)dfs(a,b+1,c^1);//拐弯
else if(y==n+1)dfs(a+1,b,c^1);
else if(x==0)dfs(a,b+1,c^1);
else if(y==0)dfs(a+1,b,c^1);
else dfs(x,y,c);
}
int main(){
cin>>n;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)cin>>g[i][j];
dfs(1,1,0);
return 0;
}