dfs

1.Lake Counting
最基础的dfs

#include<iostream>
#define Maxn 105
#define Maxm 105
using namespace std;

char a[Maxn][Maxm];
int n,m;

void dfs(int y,int x){
	a[y][x] = '.';//将走过的地方赋值为. 防止之后再走到这个位置
	
	for(int dy = -1;dy <= 1;dy++){
		for(int dx = -1;dx <= 1;dx++){//八分方向
			int ny = y + dy,nx = x + dx;
			
			if(ny >= 0 && ny < n && nx >= 0 && nx < m && a[ny][nx] == 'W') dfs(ny,nx);//符合条件的才能进行下一次dfs
		}
	}
	
	return;
}

int main(){
	
	cin >> n >> m;
	
	int ans = 0;
	for(int i = 0;i < n;i++)
		for(int j = 0;j < m;j++)
			cin >> a[i][j];
	for(int i = 0;i < n;i++){
		for(int j = 0;j < m;j++){
			if(a[i][j] == 'W'){
				dfs(i,j);
				ans++;
			}
		}
	}
	cout << ans << endl;
	return 0;
}

2.red and black

#include<iostream>
#define maxn 25
using namespace std;

char mi[maxn][maxn];
int ans , n , m;
int dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1};//上下左右四个方向
int sx,sy;

void dfs(int y,int x){
	mi[y][x] = '#';//将走过的地方赋值为#
	
	for(int i = 0;i < 4;i++){
		
		int ny = y + dy[i],nx = x + dx[i];
		
		if(ny >= 0 && ny < n && nx >= 0 && nx < m && mi[ny][nx] == '.'){//符合条件的才能进行dfs
			ans++;
			dfs(ny,nx);
		}
	}
	
}

int main(){
	
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);//关闭同步流
	
	while(cin >> m >> n, m && n){
		
		ans = 1;//起点本身也算一块
		for(int i = 0;i < n;i++)
			for(int j = 0;j < m;j++){
				cin >> mi[i][j];
				if(mi[i][j] == '@') sy = i,sx = j;//记录起点
			}
		dfs(sy,sx);
		cout << ans << '\n'; 
	}
	return 0;
}

3.N皇后问题

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

const int maxn = 15;
int queen[maxn],n;
int vis[maxn],ans;//记忆化搜索

void dfs(int pos){//前面的pos - 1个皇后都摆放好了才会进行到这一步
	
	if(pos == n){//如果到了第n个皇后(从0皇后开始)
		ans++;就说明之前的每个皇后都摆放好了,答案加1
		return;
	}
	
	for(int i = 0;i < n;i++){//从第0列开始查找,看看放到这一列是否可行
		int j;
		for(j = 0;j < pos;j++)//从第0个皇后开始查找,看看这个皇后是否与现在摆放的皇后位置冲突
			if(queen[j] == i || abs(i - queen[j]) == abs(pos - j)) break;
			//如果第j个皇后在第i列,或者第j个皇后所在的列和现在摆放的列的差
			//等于了现在摆放的第pos个皇后也就是第pos行与第j个皇后也就是第j行的差就退出
		if(j == pos){//如果这个查找到第j个皇后都没有退出过等于了pos,说明之前的所有位置都没有冲突过,就把第pos个皇后放到第i列的位置上
			queen[pos] = i;
			dfs(pos + 1);
		}
	}
}

int main(){
	
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0); 
	memset(vis,-1,sizeof(vis));
	while(cin >> n && n){
		ans = 0;
		if(vis[n] >= 0) cout << vis[n] << '\n';//如果这个数组没有被用过就继续
		else{
			dfs(0);//从第0个皇后开始搜索
			vis[n] = ans;//将答案赋值给记忆化数组,这样重复输入一个数的时候可以直接o(1)给出答案
			cout << vis[n] << '\n';
		}
	}
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值