通过重要实例深化搜索思想(DFS篇)

0.DFS题单

二话不说上代码

1.P1706 全排列问题

#include<bits/stdc++.h>
using namespace std;
int n;
int a[20];
bool f[50];
void dfs(int dep){
	if(dep==n+1){
		for(int j=1;j<=n;j++)
			cout<<setw(5)<<a[j];
		cout<<endl;
		return;
	}
	for(int i=1;i<=n;i++){
		if(!f[i]){
			a[dep]=i;
			f[i]=1;
			dfs(dep+1);
			f[i]=0;
		}
	}
}
int main(){
	cin>>n;
	dfs(1);
    return 0;
}

2.P1219 八皇后问题

#include<bits/stdc++.h>
using namespace std;
int n,s=0,p=0;
int a[100];
bool l[100],z[100],f[100];//l为占领的列,f为占领的左上右下对角线,z反之 
void dfs(int dep){
	if(dep==n+1){
		s++;
		cout<<"第"<<s<<"种情况:"<<endl;
		for(int j=1;j<=n;j++){
			for(int i=1;i<a[j];i++)
				cout<<"·";
			cout<<"Q ";
			for(int i=a[j]+1;i<=n;i++)
				cout<<"·";
			cout<<endl;
		}
		cout<<endl;
		return;
	}
	for(int i=1;i<=n;i++){
		if((!f[i+dep])&&(!z[i-dep])&&(!l[i])){
			a[dep]=i;
			f[i+dep]=1;
			z[i-dep]=1;
			l[i]=1;
			dfs(dep+1);
			l[i]=0;
			z[i-dep]=0;
			f[i+dep]=0;
		}
	}
}
int main(){
	cout<<"输入棋盘长宽:"<<endl;
	cin>>n;
	cout<<endl; 
	dfs(1);
	cout<<"所以"<<n<<"*"<<n<<"的棋盘共有"<<s<<"种摆放情况"<<endl;
    return 0;
}

3.P1605 迷宫

#include<bits/stdc++.h>
using namespace std;
const int N=6;
int a[N][N],M[N][N],tot=0,x,y,n,m,T,SX,SY,FX,FY,p;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
void dfs(int x,int y){
	if(x==FX&&y==FY){
		tot++; 
		return;
	}
	else{
		for(int p=0;p<4;p++){
			int nx=x+dx[p];
			int ny=y+dy[p];
			if(a[nx+dx[p]][ny+dy[p]]==1&&M[nx+dx[p]][ny+dy[p]]==1){
				a[nx][ny]=0;
				dfs(nx,ny);
				a[nx][ny]=1;
			}
		}
	}
}
int main(){
	cin>>n>>m>>T>>SX>>SY>>FX>>FY;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			a[i][j]=1;
			M[i][j]=1;
		}
	}
	a[SX][SY]=0;
	for(int i=1;i<=T;i++){
		cin>>x>>y;
		M[x][y]=0;
	}
	dfs(SX,SY);
	cout<<tot<<endl;
	return 0;
}

4.T235789 最大黑区域

#include<bits/stdc++.h>
using namespace std;
const int N=110;
int a[N][N],tot,n,m,p,ans=0;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
void dfs(int x,int y){
	a[x][y]=0;
	tot++;
	for(int p=0;p<4;p++){
		if(a[x+dx[p]][y+dy[p]]){
			dfs(x+dx[p],y+dy[p]);
		}
	}
}
int main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++)
			cin>>a[i][j];
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			if(a[i][j]==1){
				tot=0;//!!!
				dfs(i,j);
				if(tot>ans) 
					ans=tot;
			}
		}
	}
	cout<<ans<<endl;
	return 0;
}

“最大黑区域”此题不能错过BFS算法,一题多解有助于预防老年痴呆


天下搜索,唯熟不破

剪枝在手,动规拿走

posted @ 2023-08-23 09:47  CultReborn  阅读(10)  评论(0)    收藏  举报