AcWing
  • 首页
  • 题库
  • 题解
  • 分享
  • 问答
  • 活动
  • 应用
  • 吐槽
  • 登录/注册

AcWing 1113. 红与黑

作者: 作者的头像   qsmy_41 ,  2021-01-12 08:05:53 ,  阅读 8


0


bfs

#include <bits/stdc++.h>
using namespace std;
const int N=25;
int w, h, tt, hh;
char g[N][N];
pair<int,int> q[N*N];
int dx[]={1,0,-1,0}, dy[]={0,-1,0,1};

int bfs(int x, int y) {
    hh=0, tt=0, q[0]={x, y};
    int res=0;
    g[y][x]='#';
    while (hh<=tt) {
        res++;
        auto cur=q[hh++];
        for (int i=0; i<4; i++) {
            int a=cur.first+dx[i], b=cur.second+dy[i];
            if (a>=0 && a<w && b>=0 && b<h && g[b][a]=='.') {
                g[b][a]='#';
                q[++tt]={a, b};
            }
        }
    }
    return res;
}

int main() {
    while (cin>>w>>h, w||h) {
        int x, y;
        for (int i=0; i<h; i++) for (int j=0; j<w; j++) {
            cin>>g[i][j];
            if (g[i][j]=='@') x=j, y=i;
        }
        cout<<bfs(x, y)<<endl;
    }
    return 0;
}

dfs

#include <bits/stdc++.h>
using namespace std;
const int N=25;
int w, h;
char g[N][N];
int dx[]={1, 0, -1, 0}, dy[]={0, -1, 0, 1};

int dfs(int x, int y) {
    int res=1;
    g[y][x]='#';
    for (int i=0; i<4; i++) {
        int a=x+dx[i], b=y+dy[i];
        if (a>=0 && a<w && b>=0 && b<h && g[b][a]=='.') res+=dfs(a, b);
    }
    return res;
}

int main() {
    while (cin>>w>>h, w||h) {
        int x, y;
        for (int i=0; i<h; i++) for (int j=0; j<w; j++) {
            cin>>g[i][j];
            if (g[i][j]=='@') x=j, y=i;
        }
        cout<<dfs(x, y)<<'\n';
    }
    return 0;
}

0 评论

你确定删除吗?

© 2018-2021 AcWing 版权所有  |  京ICP备17053197号-1
联系我们  |  常见问题
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息