AcWing_1113 红与黑(DFS、连通块)

AcWing

1113. 红与黑

#include <bits/stdc++.h>
using namespace std;
int w, h;
const int W = 25, H = 25;
char m[H][W];
typedef pair<int, int> PII;
PII st;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
bool visited[H][W];
int dfs(PII p){
    visited[p.first][p.second] = true;
    int cnt = 1;
    for(int i = 0; i <= 3; i ++){
        PII pp = {p.first + dx[i], p.second + dy[i]};
        if(pp.first < 1 || pp.first > h || pp.second < 1 || pp.second > w) continue;
        if(m[pp.first][pp.second] == '#') continue;
        if(visited[pp.first][pp.second]) continue;
        cnt += dfs(pp);
    }
    return cnt;
}
int main(){
    while(1){
        cin >> w >> h;
        if(w == 0 && h == 0) break;
        // getchar();
        // for(int i = 1; i <= h; i ++){
        //     for(int j = 1; j <= w; j ++){
        //         m[i][j] = getchar();
        //         if(m[i][j] == '@') st = {i, j};
        //     }
        //     getchar();
        // }
        for(int i = 1; i <= h; i ++) cin >> m[i] + 1;
        for(int i = 1; i <= h; i ++) for(int j = 1; j <= w; j ++)
            if(m[i][j] == '@') st = {i, j};
        memset(visited, false, sizeof visited);
        int cnt = dfs(st);
        cout << cnt << '\n';
    }
    return 0;
}