AC1113红与黑(搜索算法)

y总说这叫洪水灌溉算法(flood fill算法)

具体的实现就是通过两种搜索算法来类似的在方格上模拟类似洪水水流似的来覆盖方块

题目链接


就是普普通通的搜索吧

注意这题有个坑就是行宽不是按顺序给的

// bfs

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <map>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <sstream>
#define ll long long
#define re return
#define x first
#define y second

using namespace std;

typedef pair<int, int> PII;

int w, h;
char mapp[30][30];
bool vis[30][30];

int bfs(PII start){
	int cnt = 1;
	queue<PII> q;
	
	q.push(start);
	
	int dx[4] = {-1,0,1,0};
    int dy[4] = {0,1,0,-1};
	
	while(!q.empty()){
		PII f = q.front();
		q.pop();
		
		for(int i = 0; i < 4; i++){
			int x = f.x + dx[i];
			int y = f.y + dy[i];
			
			if(x < 0 || x >= w || y < 0 || y >= h) continue;
			if(mapp[x][y] == '#') continue;
			if(vis[x][y]) continue;
			if(mapp[x][y] == '.'){
				cnt++;
				vis[x][y] = 1;
				q.push({x, y});	
			}
		}
	}
	
	return cnt;
}

int main(){
	while(cin >> h >> w && w && h){
		for(int i = 0; i < w; i++){
			scanf("%s",mapp[i]);
		}
		PII start;
		for(int i = 0; i < w; i++){
			for(int j = 0; j < h; j++){
				if(mapp[i][j] == '@'){
					start = {i, j};
					break;
				}
			}
		}
		cout << bfs(start) << endl;
	}
	return 0;
}
// dfs
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <map>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <sstream>
#define ll long long
#define re return

using namespace std;

int w, h;
char mapp[30][30];

int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};

int dfs(int x, int y){
    mapp[x][y] = '#';
    int ans = 1;
    for(int i = 0; i < 4; i++){
        int a = x + dx[i];
        int b = y + dy[i];
        if(a >= 0 && a < w && b >= 0 && b < h && mapp[a][b] == '.') ans += dfs(a, b);
    }
    return ans;
}

int main(){
	while(cin >> h >> w && w && h){
		for(int i = 0; i < w; i++){
			scanf("%s",mapp[i]);
		}
		int x, y;
		for(int i = 0; i < w; i++){
			for(int j = 0; j < h; j++){
				if(mapp[i][j] == '@'){
					x = i;
					y = j;
					break;
				}
			}
		}
		cout << dfs(x, y) << endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值