瓷砖—广搜 题解

· · 个人记录

Description

在一个 w×h 的矩形广场上,每一块 1×1 的地面都铺设了红色或黑色的瓷砖。小林同学站在某一块黑色的瓷砖上,他可以从此处出发,移动到上、下、左、右四个相邻的且是黑色的瓷砖上。现在,他想知道,通过重复上述移动所能经过的黑色瓷砖数。

Input

第 1 行为 h、w,2≤w、h≤50,之间由一个空格隔开;

以下为一个 w 行 h 列的二维字符矩阵,每个字符为“.”“#”“@”,分别表示该位置为黑色的瓷砖、红色的瓷砖、小林的初始位置。

Output

输出一行一个整数,表示小林从初始位置出发经过的黑色瓷砖数。

Sample Input

11 9

.#.........

.#.#######.

.#.#.....#.

.#.#.###.#.

.#.#..@#.#.

.#.#####.#.

.#.......#.

.#########.

...........

Sample Output

59

分析

广搜模版

代码

#include<bits/stdc++.h>
using namespace std;
int n,m,sx,sy,ans;
int a[60][60];
struct node{
    int x,y;
};
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};//方向 
queue<node>q;
int bfs(node s){//广搜 
    q.push(s);
    a[s.x][s.y]='#';
    ans++;
    while(!q.empty()){
        node u=q.front();
        q.pop();
        for(int i=0;i<4;i++){
            int xx=dx[i]+u.x;
            int yy=dy[i]+u.y;
            if(xx>0&&yy>0&&xx<=n&&yy<=m&&a[xx][yy]=='.'){

                ans++;
                q.push({xx,yy});
                a[xx][yy]='#';//标记 
            }
        }
    }


}
int main(){
    cin>>m>>n;
    char c;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            cin>>c;
            a[i][j]=c;
            if(c=='@'){
                sx=i;sy=j;//初始位置
            }
        }
    }
    bfs({sx,sy});
    cout<<ans<<endl;


    return 0;
}