可以采用DFS的思想,对于每个油田判断其周围8个位置是否有油田,一直递归下去,然后计数即可:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 100 + 10;
int m, n, num;
char matrix[N][N];
bool oil[N][N];
int pos[8][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, 1}, {1, -1}, {-1, -1}};
void dfs(int x, int y){
for(int i = 0; i < 8; i ++ ){
int nx = x + pos[i][0];
int ny = y + pos[i][1];
if(nx < 0 || nx >= m || ny < 0 || ny >= n || oil[nx][ny] || matrix[nx][ny] == '*') continue;
oil[nx][ny] = true;
dfs(nx, ny);
}
}
int main(){
while(scanf("%d%d", &m, &n) != EOF && m){
for(int i = 0; i < m; i ++ ){
scanf("%s", &matrix[i]);
}
memset(oil, false, sizeof(oil));
num = 0;
for(int i = 0; i < m; i ++ ){
for(int j = 0; j < n; j ++ ){
if(matrix[i][j] == '@' && !oil[i][j]){
oil[i][j] = true;
num++;
dfs(i, j);
}
}
}
printf("%d\n", num);
}
return 0;
}
|