BFS宽度优先搜索/DFS深度优先搜索

BFS

catch that cow

先访问邻居的三个状态(n-1,t+1),(n+1,t+1),(2n,t+1)
再访问邻居节点的扩展结点

#include
#include
#include
#include
using namespace std;
const int MAXN=100001;
struct Status{
    int n,t;
    Status(int n,int t):n(n),t(t){}
};
bool visit[MAXN];
int BFS(int n,int k){
    queue<Status> myQueue;
    myQueue.push(Status(n,0));
    visit[n]=true;
    while(!myQueue.empty()){
        Status current=myQueue.front();
        myQueue.pop();
        if(current.n==k){
            return current.t;
        }
        for(int i=0;i<3;i++){
            Status next(current.n,current.t+1);
            if(i==0){
                next.n+=1;
            }else if(i==1){
                next.n-=1;
            }else{
                next.n*=2;
            }
            if(next.n<0||next.n>MAXN||visit[next.n]){
                continue;
            }
            myQueue.push(next);
            visit[next.n]=true;
        }
    }
}
int main(){
    int n,k;
    scanf("%d%d",&n,&k);
    memset(visit,false,sizeof(visit));
    printf("%d\n",BFS(n,k));
    return 0;
}

DFS

A Knight’s Journey

#include
#include
#include
#include
using namespace std;
const int MAXN=30;
int p,q;
bool visit[MAXN][MAXN];
int direction[8][2]={
    {-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}
};
bool DFS(int x,int y,int step,string ans){
    if(step==p*q){
        cout<<ans<<endl<<endl;
        return true;
    }else{
        for(int i=0;i<8;i++){
            int nx=x+direction[i][0];
            int ny=y+direction[i][1];
            char col=ny+'A';
            char row=nx+'1';
            if(nx<0||nx>=p||ny<0||ny>=q||visit[nx][ny]){
                continue;
            }
            visit[nx][ny]=true;
            if(DFS(nx,ny,step+1,ans+col+row)){
                return true;
            }
            visit[nx][ny]=false;
        }
    }
    return false;
}
int main(){
    int n;
    scanf("%d",&n);
    int caseNumber=0;
    while(n--){
        scanf("%d%d",&p,&q);
        memset(visit,false,sizeof(visit));
        cout<<"Scenerio #"<<++caseNumber<<":"<<endl;
        visit[0][0]=true;
        if(!DFS(0,0,1,"A1")){
            cout<<"impossible"<<endl<<endl;
        }
    }
    return 0;

}

你可能感兴趣的:(宽度优先,图论,c++)