这道跟前面的油田挺像的,不过从四个方向变成了八个方向
#include<cstdio> #include <cstring> using namespace std; int m, n,cnt, count; char A[101][101]; int direction[8][2]={{1,1},{1,-1},{-1,1},{-1,-1},{1,0},{0,1},{0,-1},{-1,0}}; void dfs(int i, int j) { if(i < 0|| j < 0|| i >= m|| j >= n || A[i][j] != 'W') return; else { A[i][j] = '.'; int di = i, dj = j; for(int q = 0; q < 8; ++q) dfs(di+ direction[q][0], dj+ direction[q][1]); } } int main() { while(~scanf("%d%d", &m, &n) && (m+n)) { cnt = 0; memset(A, 0, sizeof(A)); for(int i = 0; i < m; ++i) scanf("%s", A[i]); for(int i = 0; i < m; ++i) for(int j = 0; j < n; ++j) if(A[i][j] == 'W') { dfs(i, j); cnt++; } printf("%d ", cnt); } }