AcWing 1113. 红与黑

1113. 红与黑

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值