DFS写法
- (可以在搜索8个方向的时候搜索自己本身,无所谓,9个方向更加好写)
#include<bits/stdc++.h>
using namespace std;
int main(){
int n, m, xx[] = {1,1,1,-1,-1,-1,0,0,0}, yy[] = {1,-1,0,1,-1,0,1,-1,0};
while(cin >> n >> m && n){
int ans = 0;
vector<string> s(n);
bitset<110> b[110];//标记是否dfs过
for(int i = 0; i < n; i++) cin >> s[i];
function<void(int, int)> dfs;
dfs = [&](int x, int y){
b[x][y] = 1;
for(int i = 0; i < 9; i++){
// int nx = x + xx[i], ny = y + yy[i];
int nx = x + (i / 3 - 1), ny = y + (i % 3 - 1);//与上面一行的一个意思
if(~nx && ~ny && nx < n && ny < m && s[nx][ny] == '@' && !b[nx][ny]) dfs(nx, ny);
}
};
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(s[i][j] == '@' && !b[i][j]) ans++, dfs(i, j);
cout << ans << endl;
}
return 0;
}