y总说这叫洪水灌溉算法(flood fill算法)
具体的实现就是通过两种搜索算法来类似的在方格上模拟类似洪水水流似的来覆盖方块
就是普普通通的搜索吧
注意这题有个坑就是行宽不是按顺序给的
// bfs
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <map>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <sstream>
#define ll long long
#define re return
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
int w, h;
char mapp[30][30];
bool vis[30][30];
int bfs(PII start){
int cnt = 1;
queue<PII> q;
q.push(start);
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};
while(!q.empty()){
PII f = q.front();
q.pop();
for(int i = 0; i < 4; i++){
int x = f.x + dx[i];
int y = f.y + dy[i];
if(x < 0 || x >= w || y < 0 || y >= h) continue;
if(mapp[x][y] == '#') continue;
if(vis[x][y]) continue;
if(mapp[x][y] == '.'){
cnt++;
vis[x][y] = 1;
q.push({x, y});
}
}
}
return cnt;
}
int main(){
while(cin >> h >> w && w && h){
for(int i = 0; i < w; i++){
scanf("%s",mapp[i]);
}
PII start;
for(int i = 0; i < w; i++){
for(int j = 0; j < h; j++){
if(mapp[i][j] == '@'){
start = {i, j};
break;
}
}
}
cout << bfs(start) << endl;
}
return 0;
}
// dfs
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <map>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <sstream>
#define ll long long
#define re return
using namespace std;
int w, h;
char mapp[30][30];
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
int dfs(int x, int y){
mapp[x][y] = '#';
int ans = 1;
for(int i = 0; i < 4; i++){
int a = x + dx[i];
int b = y + dy[i];
if(a >= 0 && a < w && b >= 0 && b < h && mapp[a][b] == '.') ans += dfs(a, b);
}
return ans;
}
int main(){
while(cin >> h >> w && w && h){
for(int i = 0; i < w; i++){
scanf("%s",mapp[i]);
}
int x, y;
for(int i = 0; i < w; i++){
for(int j = 0; j < h; j++){
if(mapp[i][j] == '@'){
x = i;
y = j;
break;
}
}
}
cout << dfs(x, y) << endl;
}
return 0;
}