ACM Red and Black

以‘@’为起点使用bfs对进行广度搜索,当没有黑色的地板可以前进时,也就是说周围都是红色地板的时候,搜索结束,记录已经走过的地板数,即可得到结果。

#include 
#include 
#include 


using namespace std;

const int maxn=105;
char Map[maxn][maxn];
int n,m,cnt=0;
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node
{
    int x;
    int y;
}now,next;
void BFS(int x,int y)
{
    now.x=x;
    now.y=y;
    Map[x][y]='#';
    cnt++;
    queue<node> q;
    q.push(now);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            int xx=now.x+dir[i][0];
            int yy=now.y+dir[i][1];
            if(xx>=0&&xx<n&&yy>=0&&y<m&&Map[xx][yy]=='.')
            {
                Map[xx][yy]='#';
                cnt++;
                next.x=xx;
                next.y=yy;
                q.push(next);
            }
        }
    }
}
int main()
{
    while((~scanf("%d%d",&m,&n))&&!(n==0&&m==0))
    {
        cnt=0;
        if(n==0)
            break;
        for(int i=0;i<n;i++)
        {
            scanf("%s",Map[i]);
        }
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(Map[i][j]=='@')
                {
                    BFS(i,j);
                }
            }
        }
        printf("%d\n",cnt);
    }
    return 0;
}

你可能感兴趣的:(C++)