这题一道深搜的简单题目,其实题目的思路就只是向八个方向搜索,然后把整个油田遍历一遍即可。
#include <cstdio>
#include <cstring>
int map[105][105];
int vis[105][105];
char l[105];
int n, m, color, ans;
int d[8][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}};
void dfs(int r,int c)
{
vis[r][c] = color;
for (int i = 0; i < 8;i++) {
int row = r + d[i][0];
int col = c + d[i][1];
if (row<0||col<0||row>=m||col>=n)
continue;
if (map[row][col]&&!vis[row][col])
dfs(row, col);
}
}
int main()
{
while (scanf("%d%d",&m,&n)==2&&m) {
memset(map, 0, sizeof(map));
memset(vis, 0, sizeof(vis));
for (int i = 0; i < m;i++) {
scanf("%s", &l);
for (int j = 0; j < n;j++) {
if (l[j]=='@')
map[i][j] = 1;
}
}
color = 0;
for (int i = 0; i < m;i++) {
for (int j = 0; j < n;j++) {
if (!vis[i][j]&&map[i][j]) {
color++;
dfs(i,j);
}
}
}
printf("%d\n",color);
}
return 0;
}