bfs 广度优先遍历 $O(nm)$
C++ 代码
//o(nm) bfs
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 21;
int w, h;
char g[N][N];
typedef pair<int, int> PII;
int bfs(int x, int y){
queue<PII> q;
q.push({x, y});
g[x][y] = '#';
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int res = 0;
while (q.size()){
auto t = q.front();
q.pop();
res ++;
for (int i = 0; i < 4; i ++ ){
int a = t.first + dx[i], b = t.second + dy[i];
if (a < 0 || a >= h || b < 0 || b >= w || g[a][b] != '.') continue;
g[a][b] = '#';
q.push({a, b});
}
}
return res;
}
int main(){
while (cin >> w >> h, w || h){
for (int i = 0; i < h; i ++ ) cin >> g[i];
int x, y;
for (int i = 0; i < h; i ++ )
for (int j = 0; j < w; j ++ ){
if (g[i][j] == '@'){
x = i, y = j;
}
}
cout << bfs(x, y) << endl;
// cout << dfs(x, y) << endl;
}
return 0;
}
dfs 深度优先遍历
C++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 21;
int w, h;
char g[N][N];
typedef pair<int, int> PII;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int dfs(int x, int y){
g[x][y] = '#';
int res = 1;
for (int i = 0; i < 4; i ++ ){
int a = x + dx[i], b = y + dy[i];
if (a >= 0 && a < h && b >= 0 && b < w && g[a][b] == '.'){
res += dfs(a, b);
}
}
return res;
}
int main(){
while (cin >> w >> h, w || h){
for (int i = 0; i < h; i ++ ) cin >> g[i];
int x, y;
for (int i = 0; i < h; i ++ )
for (int j = 0; j < w; j ++ ){
if (g[i][j] == '@'){
x = i, y = j;
}
}
cout << dfs(x, y) << endl;
}
return 0;
}