红与黑 《BFS》

有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。你站在其中一块黑色的瓷砖上,只能向相邻的黑色瓷砖移动。请写一个程序,计算你总共能够到达多少块黑色的瓷砖。Input包括多个数据集合。每个数据集合的第一行是两个整数W和H,分别表示x方向和y方向瓷砖的数量。W和H都不超过20。在接下来的H行中,每行包括W个字符。每个字符表示一块瓷砖的颜色,规则如下 
1)‘.’:黑色的瓷砖; 
2)‘#’:白色的瓷砖; 
3)‘@’:黑色的瓷砖,并且你站在这块瓷砖上。该字符在每个数据集合中唯一出现一次。 
当在一行中读入的是两个零时,表示输入结束。 
Output对每个数据集合,分别输出一行,显示你从初始位置出发能到达的瓷砖数(记数时包括初始位置的瓷砖)。Sample Input

6 9 
....#. 
.....# 
...... 
...... 
...... 
...... 
...... 
#@...# 
.#..#. 
0 0

Sample Output

45

BFS裸跑一遍就行,记得最后+1(起始位置),然后坑点在输入,输入的是几列几行,不是几行几列

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib>
#include <map>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <cmath>
using namespace std;
#define ull unsigned long long
#define lli long long
#define pq priority_queue<int>
#define pql priority_queue<ll>
#define pqn priority_queue<node>
#define v vector<int>
#define vl vector<ll>
#define read(x) scanf("%d",&x)
#define lread(x) scanf("%lld",&x);
#define pt(x) printf("%d
",(x))
#define YES printf("YES
");
#define NO printf("NO
");
#define gcd __gcd
#define out(x) cout<<x<<endl;
#define over cout<<endl;
#define rep(j,k) for (int i = (int)(j); i <= (int)(k); i++)
#define input(k) for (int i = 1; i <= (int)(k); i++)  {scanf("%d",&a[i]) ; }
#define mem(s,t) memset(s,t,sizeof(s))
#define ok return 0;
#define TLE std::ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define mod(x) ((x)%9973)
#define test cout<<"     ++++++      "<<endl;
//二叉树
#define lson rt<<1, l, m
#define rson rt<<1|1, m+1, r
//线段树
#define ls now<<1
#define rs now<<1|1
const int MAXN = 2e5+5;
//int dir[6][3] = {0,0,1,0,0,-1,1,0,0,-1,0,0,0,1,0,0,-1,0};
int dir[4][2] = {1,0,-1,0,0,1,0,-1}; //单位移动
//int dir[8][2] = {2,1,2,-1,-2,1,-2,-1,1,2,1,-2,-1,2,-1,-2};
int t,n,m,x,y,col,ex,ey,ans,ly,flag;
struct node
{
    int id;
    int x,y;
};
node no,nx;

char str[20+5][20+5];
int main()
{
    TLE;
    while(cin>>n>>m&&n&&m)
    {
        for(int i=0; i<m; i++)
            for(int j=0; j<n; j++)
            {
                cin>>str[i][j];
                if(str[i][j]=='@')
                    no.x=i,no.y=j,no;
            }
        queue<node>q;
        q.push(no);
        ans = 0;
        str[no.x][no.y] = '#';
        while(!q.empty())
        {
            nx = q.front();
            q.pop();
            for(int i=0; i<4; i++)
            {
                no.x = nx.x+dir[i][0];
                no.y = nx.y+dir[i][1];
                if(no.x<0 || no.y<0 ||no.x>=m ||no.y>=n) continue;
                if( str[no.x][no.y] =='.' )
                {
                    ans++;
                    str[no.x][no.y] = '#';
                    q.push(no);
                }
            }
        }
        cout<<ans+1<<endl;
    }
    ok;
}
所遇皆星河
原文地址:https://www.cnblogs.com/Shallow-dream/p/11586337.html