1. 程式人生 > 實用技巧 >寒假每日一題 AcWing 1113. 紅與黑(連通塊內點的個數)

寒假每日一題 AcWing 1113. 紅與黑(連通塊內點的個數)

題意:求連通塊內點的個數

思路:BFS 跑一遍,看看能到達那些點,記錄下來,然後統計一下

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int vis[25][25];
int dis[4][2]= {-1,0,1,0,0,1,0,-1};
char Map[25][25];
struct node{
    int x,y;

} n1,n2;
queue<node>q;
void BFS()
{
    while(!q.empty())
    {
        n2=q.front();
        q.pop();
        
for(int i=0; i<4; i++) { int tx=n2.x+dis[i][0]; int ty=n2.y+dis[i][1]; if(vis[tx][ty]==0&&Map[tx][ty]=='.') { //cout<<tx<<" "<<ty<<endl; vis[tx][ty]=2; n1.x=tx; n1.y
=ty; q.push(n1); } } } } void init() { for(int i=0; i<30; i++) for(int j=0; j<30; j++) vis[i][j]=0; } int main(){ int n,m; while( cin>>n>>m) { init(); if(n+m==0) break; int x,y;
for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { cin>>Map[i][j]; if(Map[i][j]=='@'){ x=i; y=j; } } } n1.x=x; n1.y=y; vis[x][y]=2; q.push(n1); BFS(); int cnt=0; for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { if(vis[i][j]==2) //cout<<"*"<<" ",cnt++; cnt++; /*else cout<<Map[i][j]<<" ";*/ } // cout<<endl; } cout<<cnt<<endl; } }
View Code