kuangbin专题 专题一 简单搜索 Oil Deposits HDU - 1241

Oil Deposits HDU - 1241

题目链接:https://vjudge.net/problem/HDU-1241

题意:问有几个油田,一个油田由相邻的‘@’,组成。

思路:bfs,dfs都可以,只需要遍历地图,遇到‘@’,跑一遍搜索,标记跑过的点,然后油田数+1.

#include <iostream>
#include <cstring>
#include<vector>
#include<string>
#include <cmath>
#include <map>
#include <queue>
#include <algorithm>
using namespace std;

#define inf (1LL << 31) - 1
#define rep(i,j,k) for(int i = (j); i <= (k); i++)
#define rep__(i,j,k) for(int i = (j); i < (k); i++)
#define per(i,j,k) for(int i = (j); i >= (k); i--)
#define per__(i,j,k) for(int i = (j); i > (k); i--)

const int N = 110;
int mv[8][2] = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 },
			 { 1, 1 }, { -1, -1 }, { -1, 1 }, { 1, -1 } };
char mp[N][N];
bool vis[N][N];
int n, m;

struct node{
	int x, y;
};

inline void init(){
	rep(i, 1, n) rep(j, 1, m) vis[i][j] = false;
}

inline void input(){

	init();
	rep(i, 1, n) rep(j, 1, m) cin >> mp[i][j];
}

inline bool check(int x, int y){
	return x >= 1 && x <= n && y >= 1 && y <= m;
}

void bfs(int now_x, int now_y){

	vis[now_x][now_y] = true;

	queue<node> que;
	que.push(node{ now_x, now_y });

	while (!que.empty()){

		node tmp = que.front();
		que.pop();

		rep__(p, 0, 8){
			int dx = tmp.x + mv[p][0];
			int dy = tmp.y + mv[p][1];

			if (check(dx, dy) && !vis[dx][dy] && mp[dx][dy] == '@'){
				vis[dx][dy] = true;
				que.push(node{ dx, dy });
			}
		}
	}
}

void work(){
	
	int ans = 0;

	rep(i, 1, n) rep(j, 1, m){
		//附加条件,这个‘@’没被访问过,说明是新的油田的一部分
		if (mp[i][j] == '@' && !vis[i][j]){
			bfs(i, j);
			++ans;
		}
	}

	cout << ans << endl;
}

int main(){

	ios::sync_with_stdio(false);
	cin.tie(0);

	while (cin >> n >> m){

		if (m == 0) break;

		input();
		work();
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值