#include <iostream>
#include <queue>
#define x first
#define y second
using namespace std;
const int N = 25;
int n, m;
char g[N][N];
typedef pair<int, int> PII; //定义坐标
//四个方向的偏移量
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
int dfs(int sx, int sy)
{
//1、首先标记为已开发
//2、然后对其四个方向进行探索
//3、然后如果没用越界且可访问时 则继续dfs
g[sx][sy] = '#';
int res = 1;
for(int i = 0; i < 4; i++){
int x = sx + dx[i], y = sy + dy[i];
if(x >= 0 && x < n && y >= 0 && y < m && g[x][y] == '.')
{
res += dfs(x, y);
}
}
return res;
}
int bfs(int sx, int sy)
{
queue<PII> q;
q.push({sx, sy});
int res = 0;
while(q.size())
{
auto t = q.front();
q.pop();
res++;
//每一次遍历都将满足条件的节点放进队列中去
//最后记录下进入过队列中的节点数目,即是结果
for(int i = 0; i < 4; i++){
int a = t.x + dx[i], b = t.y + dy[i];
if(a >= n || a < 0 || b >= m || b < 0 || g[a][b] != '.') continue;
q.push({a, b});
g[a][b] = '#';
}
}
return res;
}
int main()
{
while(cin >> m >> n, n || m) //当n和m不全为0时循环继续
{
for(int i = 0; i < n; i++) cin >> g[i]; //读入一行数据
int x = 0, y = 0;
//记录下起点坐标
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(g[i][j] == '@'){
x = i;
y = j;
}
}
}
//cout << bfs(x, y) << endl;
cout << dfs(x, y) << endl;
}
return 0;
}
AcWing 1113. 红与黑
最新推荐文章于 2024-03-09 11:43:27 发布