AcWing 1097. pond count (Flood Fill)

Topic links: Click here

Here Insert Picture Description
Here Insert Picture Description

Learned two tips:

  1. Using macro definitions to simplify the code.
  2. Communicating a point eight, it can be converted to traverse around this point 3 3 3*3 matrix.
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

#define r first         // 简化代码
#define c second

using namespace std;
typedef pair<int,int> PII;
const int N = 1010, M = N * N;

int n, m;
char g[N][N];
bool st[N][N];
PII q[M];

void bfs(int x, int y)
{
    int hh = 0, tt = -1;
    q[++tt] = {x, y};
    st[x][y] = true;
    
    while(hh <= tt)
    {
        PII t = q[hh++];
        
        for(int i = t.r - 1; i <= t.r + 1; ++i)     // 遍历8个方向,即遍历3*3的矩阵
        {
            for(int j = t.c - 1; j <= t.c + 1; ++j)
            {
                if(i == t.r && j == t.c)    continue;
                if(i < 0 || i >= n || j < 0 || j >= m)  continue;
                if(g[i][j] == '.' || st[i][j])  continue;
                
                q[++tt] = {i, j};
                st[i][j] = true;
            }
        }
    }
}

int main()
{
    scanf("%d%d", &n, &m);
    for(int i = 0; i < n; ++i)  scanf("%s", g[i]);
    
    int cnt = 0;
    for(int i = 0; i < n; ++i)
    {
        for(int j = 0; j < m; ++j)
        {
            if(g[i][j] == 'W' && !st[i][j])
            {
                bfs(i, j);
                cnt++;
            }
        }
    }
    
    printf("%d\n", cnt);
    return 0;
}
Published 844 original articles · won praise 135 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_42815188/article/details/105039459