题目:http://acm.hdu.edu.cn/showproblem.php?pid=1241
给出一张地图,@代表有油,*代表没有。对于一个@,它的上下左右,左上,左下,右上,右下的位置若含有@,则它们属于同一块油田,问给出的地图中有几块油田?
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<queue>
#define pii pair<int, int>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 107;
int dir[8][2] = {1, 0, -1, 0, 0, 1, 0, -1, 1, 1, 1, -1, -1, 1, -1, -1};
char grid[MAXN][MAXN];
int m, n;
int vis[MAXN][MAXN];
int cnt = 0;
void bfs(int x, int y)
{
queue<pii> q;
q.push(pii(x, y));
while(!q.empty())
{
pii now = q.front(); q.pop();
for(int i = 0; i < 8; i++)
{
int nx = now.first + dir[i][0];
int ny = now.second + dir[i][1];
if(nx >= 0 && nx < m && ny >= 0 && ny < n
&& grid[nx][ny] != '*' && !vis[nx][ny])
{
vis[nx][ny] = 1;
q.push(pii(nx, ny));
}
}
}
}
int main()
{
while(cin >> m >> n && (m + n))
{
cnt = 0;
memset(vis, 0, sizeof(vis));
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
cin >> grid[i][j];
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(grid[i][j] == '@' && !vis[i][j])
{
cnt++;
vis[i][j] = 1;
bfs(i, j);
}
}
}
cout << cnt << endl;
}
return 0;
}