DFS BFS 学习总结

DFS 深度优先搜索

基本思路:

  if(true) 返回

  

典型例题:

  1.马走日(非常典型)

#include<iostream>
#include<cstring>
using namespace std;

int n,m,x0,y0;
int sum;
int book[100][100];//记录是否走过
int place[8][2]={-2,1,-2,-1,-1,2,-1,-2,2,1,2,-1,1,2,1,-2};
//八个方向
void dfs(int x,int y,int s){
    if(s==n*m){
        sum++;
        return;
    }
    for(int i=0;i<8;i++){
        int tx=x+place[i][0];
        int ty=y+place[i][1];
        if(tx>=0&&ty>=0&&tx<n&&ty<m&&book[tx][ty]==0){
            book[tx][ty]=1;
            dfs(tx,ty,s+1);
            book[tx][ty]=0;
        }
    }    
}
int main(){
    int T;
    cin>>T;
    while(T--){
        sum=0;
        memset(book,0,sizeof(book));
        cin>>n>>m>>x0>>y0;
        book[x0][y0]=1;
        dfs(x0,y0,1);
        cout<<sum<<endl;
    }
} 

  2.八皇后

  3.相加和位k

  

原文地址:https://www.cnblogs.com/w-w-t/p/11792464.html