9.2 DFS
A Knight’s Journey
//A Knight's Journey
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
int direction[8][12]={
{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}
};
const int MAXN=30;
bool visit[MAXN][MAXN];
bool DFS(int x,int y,int step,string answer,int p,int q){ //p和q是尺寸
if(step==p*q){
cout<<answer<<endl<<endl;
return true;
}
for(int i=0;i<8;++i){
int nx=x+direction[i][0];
int ny=y+direction[i][1];
if(nx<0||nx>=p||ny<0||ny>=q||visit[nx][ny]){
continue; //不处理
}
visit[nx][ny]=true;
char col=ny+'A';
char row=nx+'1';
if(DFS(nx,ny,step+1,answer+col+row,p,q)){
return true;
}
visit[nx][ny]=false;
}
return false;
}
int main(){
int n;
scanf("%d",&n);
int caseNumber=0;
while(n--){
int p,q;
scanf("%d%d",&p,&q);
memset(visit,false,sizeof(visit));
cout<<"Scenario #"<<++caseNumber<<":"<<endl;
visit[0][0]=true;
if(DFS(0,0,1,"A1",p,q)){
continue;
}else{
cout<<"impossible"<<endl<<endl;
}
}
return 0;
}
Square
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int MAXN=25;
int sticks[MAXN];
bool visit[MAXN];
bool DFS(int sum,int number,int side,int m){
if(number==4){
return true;
}
for(int i=0;i<m;++i){
if(visit[i]||sum+sticks[i]>side){
continue;
}
visit[i]=true;
if(sum+sticks[i]==side){
if(DFS(0,number+1,side,m)){
return true;
}
}else{
if(DFS(sum+sticks[i],number,side,m)){
return true;
}
}
visit[i]=false;
}
return false;
}
int main(){
int n;
scanf("%d",&n);
while(n--){
int m;
scanf("%d",&m);
int length=0;
for(int i=0;i<m;i++){
scanf("%d",&sticks[i]);
length+=sticks[i];
}
int side=length/4;
memset(visit,false,sizeof(visit));
if(DFS(0,0,side,m)){
printf("yes\n");
}else{
printf("no\n");
}
}
return 0;
}
Square—改进
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int MAXN=25;
int sticks[MAXN];
bool visit[MAXN];
bool DFS(int sum,int number,int position,int side,int m){
if(number==3){
return true;
}
int sample=0; //记录失败样例
for(int i=position;i<m;++i){
if(visit[i]||sum+sticks[i]>side||sticks[i]==sample){
continue;
}
visit[i]=true;
if(sum+sticks[i]==side){
if(DFS(0,number+1,0,side,m)){
return true;
}else{
sample=sticks[i];
}
}else{
if(DFS(sum+sticks[i],number,i+1,side,m)){
return true;
}
}
visit[i]=false;
}
return false;
}
bool Compare(int x,int y){
return x>y;
}
int main(){
int n;
scanf("%d",&n);
while(n--){
int m;
scanf("%d",&m);
int length=0;
for(int i=0;i<m;i++){
scanf("%d",&sticks[i]);
length+=sticks[i];
}
if(length%4!=0){
printf("no\n");
continue;
}
int side=length/4;
memset(visit,false,sizeof(visit));
sort(sticks,sticks+m,Compare);
if(sticks[0]>side){
printf("no\n");
continue;
}
if(DFS(0,0,0,side,m)){
printf("yes\n");
}else{
printf("no\n");
}
}
return 0;
}