广度优先遍历BFS
// (keng)题目是先输入的方式:列数 * 行数
/*
bfs
*/
#include <iostream>
#include <queue>
using namespace std;
const int N = 20;
char graph[N][N];
struct node{
int x, y;
};
node st;
int main(){
int n, m;
while(cin >> m >> n && m && n){
for(int i = 0; i < n ; i ++){
for(int j = 0; j < m; j ++){
cin >> graph[i][j];
if(graph[i][j] == '@') st = {i, j};
}
}
queue<node> qu;
qu.push(st);
graph[st.x][st.y] = '#';
int dx[4] = {0, -1, 0, 1}, dy[4] = {-1, 0, 1, 0};
int cnt = 1;
while(!qu.empty()){
node now = qu.front();
qu.pop();
for(int i = 0; i < 4; i ++ ){
int xx = now.x + dx[i];
int yy = now.y + dy[i];
if(xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
if(graph[xx][yy] == '#') continue;
cnt ++ ;
qu.push({xx, yy});
graph[xx][yy] = '#';
}
}
cout << cnt << endl;
}
return 0;
}
深度优先遍历DFS
/*
dfs
*/
#include <iostream>
#include <cstring>
using namespace std;
const int N = 30;
char graph[N][N];
bool vis[N][N];
typedef pair<int, int> pii;
pii st;
int n, m;
int cnt;
int dic[4][2] = {
{-1, 0}, {0, 1}, {1, 0}, {0, -1}
};
void read(){
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < m; j ++ ){
cin >> graph[i][j];
if(graph[i][j] == '@') st = {i, j};
}
}
}
bool check(int x, int y){
return x >= 0 && x < n && y >= 0 && y < m;
}
void dfs(pii loc){
for(int i = 0; i < 4; i ++ ){
int x = loc.first + dic[i][0];
int y = loc.second + dic[i][1];
if(check(x, y) && graph[x][y] == '.' && !vis[x][y]){
vis[x][y] = true;
cnt ++ ;
dfs({x, y});
}
}
}
int main(){
while(cin >> m >> n && m && n){
read();
memset(vis, false, sizeof vis);
cnt = 1;
dfs(st);
cout << cnt << endl;
}
return 0;
}