AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 应用
  • 更多
    • 题解
    • 分享
    • 商店
    • 问答
    • 吐槽
  • App
  • 登录/注册

AcWing 1113. 红与黑

作者: 作者的头像   ベ断桥烟雨ミ_53 ,  2023-02-01 15:16:23 ,  所有人可见 ,  阅读 6


0


宽搜bfs

#include <bits/stdc++.h>
using namespace std;
const int N=25;
typedef pair<int,int> PII;
#define x first
#define y second
char a[N][N];
int w,h;
int bfs(int sx,int sy)
{
    int cnt=0;
    queue<PII> q;
    q.push({sx,sy});
    a[sx][sy]='#';
    int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
    while(q.size())
    {
        PII t=q.front();
        q.pop();
        cnt++;
        for(int i=0;i<4;i++)
        {
            int x=t.x+dx[i],y=t.y+dy[i];
            //if(x<1||x>h||y<1||y>w||a[x][y]=='#')continue;
            if(a[x][y]=='.')
            {
                q.push({x,y});
                a[x][y]='#';
            }
        }
    }
    return cnt;
}
int main(){

    while(cin>>w>>h,w&&h)
    {
        int startx,starty;
        for(int i=1;i<=h;i++)
        for(int j=1;j<=w;j++)
        {
            cin>>a[i][j];
            if(a[i][j]=='@')
            {
               startx=i,starty=j; 
            }
        }
        cout<<bfs(startx,starty)<<endl;
    }
    return 0;
}

深搜dfs

#include <bits/stdc++.h>
using namespace std;
int w,h;
char g[25][25];
int dfs(int x,int y)
{
    int cnt=1;
    g[x][y]='#';
    int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
    for(int i=0;i<4;i++)
    {
        int a=x+dx[i],b=y+dy[i];
        if(a>=1&&a<=h&&b>=1&&b<=w&&g[a][b]=='.')
        {
            cnt+=dfs(a,b);
        }
    }
    return cnt;
}
int main(){
    while(cin>>w>>h,w||h)
    {
        int sx,sy;
        for(int i=1;i<=h;i++)
        for(int j=1;j<=w;j++)
        {
            cin>>g[i][j];
            if(g[i][j]=='@')
            sx=i,sy=j;
        }
        cout<<dfs(sx,sy)<<endl;
    }
    return 0;
}

0 评论

你确定删除吗?
1024
x

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