油田 bfs

#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
char a[109][109];int book[109][109];int x1,y1;
struct node
{
	int x,y;
	node(){}
	node(int xx,int yy): x(xx),y(yy){}
};
void bfs(int x,int y)
{
	queue<node>A;
	A.push(node(x,y));
	while(!A.empty())
	{
	node u=A.front();
	A.pop();
	for(int i = u.x-1;i <= u.x+1;i++)
	{
		for(int j = u.y-1;j <= u.y+1;j++)
		{
		if(i < 0 || i >= x1 || j < 0 || j >= y1)
		{
			continue;
		}
		if(a[i][j] == '@' && book[i][j] == 0)
		{
			book[i][j] = 1;
			A.push(node(i,j));
		}
		}	
	}
	} 
	
}
int main()
{
	while(1)
	{
		memset(a,0,sizeof(a));
		memset(book,0,sizeof(book));
		scanf("%d%d",&x1,&y1);
		if(x1 == 0 && y1 == 0)
		{
			break;
		}int y=0;
		for(int i=0;i<x1;i++)
		{
			for(int j=0;j<y1;j++)
			{
				cin>>a[i][j];
				
			}
		}
		for(int i=0;i<x1;i++)
		{
			for(int j=0;j<y1;j++)
			{
				if(a[i][j] == '@' && book[i][j] == 0)
				{
					bfs(i,j);
					y++;
				}
			}
		}
		
		printf("%d\n",y);	
	}
	
	return 0;
}

The eoSurvComp geologic survey company is responsible for detecting underground oil deposits. eoSurvCompworkswithonelargerectangularregionoflandatatime,andcreatesagridthatdivides the land into numerous suare plots. It then analyes each plot separately, using sensing euipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be uite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid. Input The input file containsone or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input otherwise 1 ≤ m ≤ 100 and 1 ≤ n ≤ 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either ‘ ’, representing the absence of oil, or ‘’, representing an oil pocket. Output For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horiontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.

Sample Input

1 1

*
 
3 5

*@*@*

**@**

*@*@*

 1    8

@@****@*

  5 5  

****@

*@@*@

*@**@

@@@*@

@@**@

0 0

Sample Output

0

1

2

2
 

猜你喜欢

转载自blog.csdn.net/qq_43568078/article/details/85087686
BFS