A-Oil Deposits
题意:If two pockets are adjacent(相邻的), then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.
输入:The input file contains one 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.
输出:For each grid, output the number of distinct(不同的) oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally(水平的), vertically(竖直的), or diagonally(斜对的). An oil deposit will not contain
more than 100 pockets.
(注:即油田周围一圈8个点,如果有油,则油量相同)
样例:
Sample Input:
1 1
*
3 5
@@*
@
@@*
1 8
@@***@
5 5
****@
@@@
@**@
@@@@
@@**@
0 0
Sample Output
0
1
2
2
思路(查):利用广度优先搜索(bfs),寻找一个油田周围紧邻的油田,如果找到则此部分连通图全置为vis=1, 找几次’@'则证明有几个油量不同的油田
俩种方法:(1)标记数组 (2)访问过的点改为’*’
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
const int maxn=1e2+5;
int n,m;
char map[maxn][maxn];
bool vis[maxn][maxn];//标记数组:标记是否被访问
struct Node{
int x;
int y;
};
int dx[8]={0,1,1,1,0,-1,-1,-1};
int dy[8]={-1,-1,0,1,1,1,0,-1};
void bfs(Node node_){
queue<Node> q;
vis[node_.x][node_.y]=true;
q.push(node_);
Node tmp,next;
while(!q.empty()){
tmp=q.front();
q.pop();
for(int i=0;i<8;i++){
next.x=tmp.x+dx[i];
next.y=tmp.y+dy[i];
if(next.x>=n||next.x<0||next.y<0||next.y>=m||map[next.x][next.y]=='*'){
continue;
}
if(vis[next.x][next.y]==false){
vis[next.x][next.y]=true;
q.push(next);
}
}
}
}
int main(){
while(cin>>n>>m&&n&&m){
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>map[i][j];
}
}
int ret=0;
Node tmp;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(map[i][j]=='@'&&vis[i][j]==false){
tmp.x=i;
tmp.y=j;
//这里创造一个结构体,来储存该节点下标位置
bfs(tmp);
ret++;
}
}
}
cout<<ret<<endl;
}
return 0;
}