代码如下
#include<iostream>
#include<string>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
int n,a[30][30];
void to_do(){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)
printf("%3d",a[i][j]);
cout<<endl;
}
exit(1);
return ;
}
void dfs(int h,int l,int now,string s){
a[h][l]=now;
if(now==n*n){
to_do();
return ;
}
now++;
if(s=="right"){
if(l==n||a[h][l+1]!=0) dfs(h+1,l,now,"down");
else dfs(h,l+1,now,"right");
}
else if(s=="down"){
if(h==n||a[h+1][l]!=0) dfs(h,l-1,now,"left");
else dfs(h+1,l,now,"down");
}
else if(s=="left"){
if(l==1||a[h][l-1]!=0) dfs(h-1,l,now,"up");
else dfs(h,l-1,now,"left");
}
else{
if(h==1||a[h-1][l]!=0) dfs(h,l+1,now,"right");
else dfs(h-1,l,now,"up");
}
return ;
}
int main(){
cin>>n;
if(n==1){
cout<<" 1";
return 0;
}
dfs(1,1,1,"right");
return 0;
}
为啥RE了4个点?