牛客练习赛85 A 科学家的模型 找规律 bfs

传送门

题意:

输入一个5*5的矩阵,由01两种字符组成,判断写的是什么数字,0,8或9

题解:

观察数字的特征,8这个数字里有2个互不连通且不与边界相连接的0组成的连通分量

9这个数字有一个弯钩,

01110
01010
01110
01010
01110

观察图中红色的1,它上下左右四个邻接点只有一个是1,这是9独有的特征

剩下的就是0了

AC代码:

#include<iostream>
using namespace std;
char mapp[100][100];
bool vis[100][100];
int xx[4]={1,-1,0,0};
int yy[4]={0,0,1,-1};
bool edgebfs(int x,int y){
    bool isedge=0;
    vis[x][y]=1;
    if(x==1 || y==1 || x==5 || y==5)isedge=1;
    for(int i=0;i<4;i++){
        int xr=x+xx[i];
        int yr=y+yy[i];
        if(xr>=1 && xr<=5 && yr>=1 && yr<=5 && mapp[xr][yr]=='0' && vis[xr][yr]==0){
            //cout<<"path"<<xr<<yr<<endl;
            isedge=( edgebfs(xr,yr)||isedge );
        }
    }
    
    return isedge;
}
int main(){
    for(int i=1;i<=5;i++){
        for(int j=1;j<=5;j++){
            cin>>mapp[i][j];
        }
    }
    int edgep=0;
    int nop=0;
    bool gou=0;
    for(int i=1;i<=5;i++){
        for(int j=1;j<=5;j++){
            if(mapp[i][j]=='0' && vis[i][j]==0){
                if(edgebfs(i,j)==1)edgep++;
                else nop++;
                //cout<<"point"<<i<<j<<endl;
            }
            if(mapp[i][j]=='1'){
                int tx=0;
                for(int jw=0;jw<4;jw++){
                    int xr=i+xx[jw];
                    int yr=j+yy[jw];
                    //cout<<"xr"<<xr<<"yr"<<yr<<"c"<<mapp[xr][yr]<<endl;
                    tx=tx+((mapp[xr][yr]=='1')?1:0);
                }
                if(tx==1){
                    gou=1;
                    //cout<<i<<" "<<j<<endl;
                }
            }
        }
    }
    //cout<<"edge"<<edgep<<"nop"<<nop<<endl;
    if(nop==2)cout<<8<<endl;
    else if(gou==1)cout<<9<<endl;
    else cout<<0<<endl;
    return 0;
}

 
原文地址:https://www.cnblogs.com/isakovsky/p/14932805.html