HDU 1241 Oil Deposits(BFS)

这题也是用bfs可以很轻松的搞定
计数的思路和bfs里面典型的那个小岛问题没区别

附上AC代码
往八个方向泛洪

#include<iostream>
#include<queue>
using namespace std;

int m, n;
char maze[101][101];
int tag[101][101];

struct Node{
	int x;
	int y;
	Node(int x, int y){
		this->x = x;
		this->y = y;
	}
};

void bfs(int x, int y)
{
	queue<Node> q;
	q.push(Node(x, y));
	tag[x][y] = 1;
	while(!q.empty())
	{
		Node f = q.front();
		if(f.x - 1 >= 1 && f.x - 1 <= m && maze[f.x - 1][f.y] == '@'
		&& tag[f.x - 1][f.y] == 0)
		{
			tag[f.x - 1][f.y] = 1;
			maze[f.x - 1][f.y] = '.';			//已走到的就改掉 
			q.push(Node(f.x - 1, f.y)); 
		}	
		if(f.x - 1 >= 1 && f.x - 1 <= m && f.y + 1 >= 1 && f.y + 1 <= n
		&& maze[f.x - 1][f.y + 1] == '@' && tag[f.x - 1][f.y + 1] == 0)
		{
			tag[f.x - 1][f.y + 1] = 1;
			maze[f.x - 1][f.y + 1] = '.';
			q.push(Node(f.x - 1, f.y + 1)); 
		}		
		if(f.y + 1 >= 1 && f.y + 1 <= n && maze[f.x][f.y + 1] == '@'
		&& tag[f.x][f.y + 1] == 0)
		{
			tag[f.x][f.y + 1] = 1;
			maze[f.x][f.y + 1] = '.';
			q.push(Node(f.x, f.y + 1)); 
		}		
		if(f.x + 1 >= 1 && f.x + 1 <= m && f.y + 1 >= 1 && f.y + 1 <= n
		&& maze[f.x + 1][f.y + 1] == '@' && tag[f.x + 1][f.y + 1] == 0)
		{
			tag[f.x + 1][f.y + 1] = 1;
			maze[f.x + 1][f.y + 1] = '.';
			q.push(Node(f.x + 1, f.y + 1)); 
		}			
		if(f.x + 1 >= 1 && f.x + 1 <= m && maze[f.x + 1][f.y] == '@'
		&& tag[f.x + 1][f.y] == 0)
		{
			tag[f.x + 1][f.y] = 1;
			maze[f.x + 1][f.y] = '.';
			q.push(Node(f.x + 1, f.y)); 
		}
		if(f.x + 1 >= 1 && f.x + 1 <= m && f.y - 1 >= 1 && f.y - 1 <= n
		&& maze[f.x + 1][f.y - 1] == '@' && tag[f.x + 1][f.y - 1] == 0)
		{
			tag[f.x + 1][f.y - 1] = 1;
			maze[f.x + 1][f.y - 1] = '.';
			q.push(Node(f.x + 1, f.y - 1)); 
		}	
		if(f.y - 1 >= 1 && f.y - 1 <= n && maze[f.x][f.y - 1] == '@'
		&& tag[f.x][f.y - 1] == 0)
		{
			tag[f.x][f.y - 1] = 1;
			maze[f.x][f.y - 1] = '.';
			q.push(Node(f.x, f.y - 1)); 
		}
		if(f.x - 1 >= 1 && f.x - 1 <= m && f.y - 1 >= 1 && f.y - 1 <= n
		&& maze[f.x - 1][f.y - 1] == '@' && tag[f.x - 1][f.y - 1] == 0)
		{
			tag[f.x - 1][f.y - 1] = 1;
			maze[f.x - 1][f.y - 1] = '.';
			q.push(Node(f.x - 1, f.y - 1)); 
		}
		q.pop();
	}
}

void Clear(int m, int n)
{
	for(int i = 1;i <= m;i++)
	{
		for(int j = 1;j <= n;j++)
		{
			tag[i][j] = 0;
		} 
	}
}

int main()
{
	while(true)
	{
		cin >> m >> n;
		if(m == 0 && n == 0)
			break;
		for(int i = 1;i <= m;i++)
		{
			for(int j = 1;j <= n;j++)
			{
				cin >> maze[i][j];
			}
		}
		int cnt = 0;
		for(int i = 1;i <= m;i++)
		{
			for(int j = 1;j <= n;j++)
			{
				if(maze[i][j] == '@')
				{
					bfs(i, j);		//如果找到一个@, 那么用bfs把和它相关的点都泛掉 
					cnt++;
				}
			}
		}
		cout << cnt << endl;
		Clear(m, n);
	}
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值