2 solutions

  • 0
    @ 2022-4-12 17:52:53

    bfs

    #include<iostream>
    #include<queue>
    using namespace std;
    typedef pair<int,int> PAII;
    const int N=150;
    char ch[N][N];
    int n,m,sum;
    bool st[N][N];
    int dx[8]={1,-1,0,0,-1,1,-1,1};
    int dy[8]={0,0,-1,1,-1,1,1,-1};
    int bfs(int x,int y)
    {
    	queue<PAII> q;
    	for(int i=0;i<n;i++)
    	{
    		for(int j=0;j<m;j++)
    		{
    			if(ch[i][j]=='W'&&!st[i][j])
    			{
    				sum++;
    				q.push({i,j});
    				st[i][j]=true;
    				while(q.size())
    				{
    					auto t=q.front();
    					q.pop();
    					int a=t.first,b=t.second;
    					for(int k=0;k<8;k++)
    					{
    						int xx=a+dx[k],yy=b+dy[k];
    						if(xx>=0&&yy>=0&&xx<n&&yy<m&&ch[xx][yy]=='W'&&!st[xx][yy])
    						{
    							q.push({xx,yy});
    							st[xx][yy]=true;
    						}
    					}
    				}
    			}
    		}
    	}
    	return sum;
    }
    int main(){
    	cin>>n>>m;
    	for(int i=0;i<n;i++)
    		for(int j=0;j<m;j++)
    			cin>>ch[i][j];
    	int t=bfs(0,0);
    	cout<<t;
    	return 0;
    }
    

    Information

    ID
    772
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    3
    Tags
    # Submissions
    66
    Accepted
    36
    Uploaded By