【L - Oil Deposits】

80 篇文章 0 订阅
80 篇文章 0 订阅

思路:

  • BFS,记录联通块(实际就是记录经过几次BFS)。

代码:

  • 46ms 1428kB
//46ms		1428kB 


#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

const int maxn = 105;
const int moveto[8][2] = {1,0 , -1,0 , 0,1 , 0,-1 , -1,-1 , 1,1 , 1,-1 , -1,1};

bool mp [maxn][maxn];
bool vis[maxn][maxn];
int M,N;
struct grid{
	int x,y;
	grid (int x,int y) : x(x) , y(y) {} ;
};
queue<grid> Q;
int ans;
void init(){
	memset(mp , false , sizeof(mp)) ;
	memset(vis ,false , sizeof(vis));
	while(Q.size())
		Q.pop();
	ans = 0;
	return ;
}

void BFS(){
	while(memcmp(vis , mp , sizeof(mp))){
		ans++;
		int stx,sty;
		for(stx=1;stx<=M;stx++){
			for(sty=1;sty<=N;sty++)
				if(mp[stx][sty] && !vis[stx][sty])
					break;
			if(mp[stx][sty] && !vis[stx][sty])
				break;//这个不要忘 
		}//大括号不要忘,这个循环要认真写 
		Q.push(grid(stx,sty));vis[stx][sty] = true;
		while(Q.size()){
			grid cur = Q.front() ; Q.pop() ;
			int x = cur.x ; int y = cur.y ;
			for(int i=0;i<8;i++){
				int nx = x + moveto[i][0];
				int ny = y + moveto[i][1];
				if(nx < 1 || ny < 1 || nx > M || ny > N)
					continue;
				if(mp[nx][ny] && !vis[nx][ny]){
					Q.push(grid(nx , ny));
					vis[nx][ny] = true;
				}
			}
		}
	}
	return ;
}

int main(){
	while(cin>>M>>N && M){
		init();
		for(int i=1;i<=M;i++){
			for(int j=1;j<=N;j++){
				char te;//temp
				cin>>te;
				if(te == '@')
					mp[i][j] = true;
			}
		}
		BFS();
		cout<<ans<<endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值