hdu_1241_Oil Deposits(BFS)

<span style="font-size:24px;">题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1241
</span>
<span style="font-size:24px;">/*算法思路:从字符数组oil的第一元素开始,遍历整个数组,
当遇到'@’时,进入队列push,立即更新此字符为‘* ’,调用bfs(),
while循环,结束条件是队列为空,出列pop,在此字符上的8个方向上进行一次遍历,
并入列,且及时更新该字符为‘* ’   …  */
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int r,c,dx[8] = {0,1,1,1,0,-1,-1,-1},dy[8] = {1,1,0,-1,-1,-1,0,1};
char oil[101][101];
typedef pair<int,int> P;
P p;//使用pair类型存储每一个字符所在的坐标:横坐标 p.first 纵坐标p.second 
queue<P> que; //队列的元素是pair类型 

//广度优先搜索 
void bfs()
{
	while(!que.empty())  // que.empty()队列为空返回真值 
	{
	  	p = que.front();
		que.pop();
		int xx = p.first;
		int yy = p.second;
		
		int i,j,x1,y1;
		for(i = 0;i < 8;i++)//8个方向  
		{
			x1 = xx + dx[i];
			y1 = yy + dy[i];
			if(x1 >= 0 || x1 < c || y1 >= 0 || y1 < r)//x1不能超过列坐标,y1不能超过行坐标 
			//if(x1 >= 0 && x1 < c && y1 >= 0 && y1 < r)我对这个有疑问,为什么不能用&& 
			{
				
				if(oil[x1][y1] == '@')
				{
					oil[x1][y1] = '*';//更新已访问过的值,避免下次的访问 
					p.first = x1;
					p.second = y1;
					que.push(p); 
				}
			}	
		}
	}
	
}
int main(int argc, char *argv[])
{
	while(1)
	{
		int r,c;
		cin >> r >> c;
		if(r == 0 && c == 0)
			return 0;
			
		int i,j;
		for(i = 0;i < r;i++)
			for(j = 0;j < c;j++)
					cin >> oil[i][j];
		
		int count = 0;	
		for(i = 0;i < r;i++)
		{
			for(j = 0;j < c;j++)
			{
				if(oil[i][j] == '@')
				{
					count++;
					oil[i][i] = '*';//更新已访问过的值,避免下次的访问 
					p.first = i;
					p.second = j;
					que.push(p);
					bfs();
				}	
			}
		}	
		cout << count << endl;	
	}
	return 0;
}</span>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值