Bfs算法1.2

题目大意: 
有一块地有一些石油。“@”代表着这是石油,“#”代表着这不是石油。若两块石油相邻,则认为他们是一块石油。请问这块地里一共有多少块石油?

bfs做法:

#include<bits/stdc++.h>
using namespace std;
const int maxn=100+5;
int dx[]= {-1,1,0,0};
int dy[]= {0,0,-1,1};
int sr,sc,er,ec;
int n,m;
struct Node
{
    int r,c;
    Node() {}
    Node(int r,int c):r(r),c(c) {}
};
char mp[maxn][maxn];
void  BFS(Node sta)
{
    mp[sta.r][sta.c]='.';
    queue<Node> Q;
    Q.push(Node(sta.r,sta.c));
    while(!Q.empty())
    {
        Node x=Q.front();
        Q.pop();
        for(int i=0; i<4; i++)
        {
            int nr=x.r+dx[i];
            int nc=x.c+dy[i];
            if(nr>=1 && nr<=n && nc>=1 && nc<=m && mp[nr][nc]=='@')
            {
                mp[nr][nc]='.';
                Q.push(Node(nr,nc));
            }
        }
    }
}
int main()
{
    while(cin>>n>>m)
    {
        int tot=0;
        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=m; j++)
            {
                cin>>mp[i][j];
            }

        }
        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=m; j++)
            {
                if(mp[i][j]=='@')
                {
                    Node ok=Node(i,j);
                    BFS(ok);
                    ++tot;
                }
            }

        }
        cout<<tot<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lanshan1111/article/details/83042949