(BFS 3184) 양(C++)

소스 코드

#include <iostream>
using namespace std;

int r, c;
char graph(251)(251);
int visited(251)(251);
int sheep = 0, wolf = 0;

int dx(4) = {1, -1, 0, 0};
int dy(4) = {0, 0, 1, -1};

int sheep_ans = 0;
int wolf_ans = 0;

void dfs(int x, int y) {
    visited(x)(y) = 1;
    
    if(graph(x)(y) == 'o') sheep++;
    else if(graph(x)(y) == 'v') wolf++;
    
    for(int i=0; i<4; i++) {
        int nx = x + dx(i);
        int ny = y + dy(i);
        
        if(nx < 0 || ny < 0 || nx >=r || ny >=c) continue;
        if(visited(nx)(ny) == 0 && graph(x)(y) != '#') dfs(nx, ny);
    }
}

int main() {
    cin >> r >> c;
    
    for(int i=0; i<r; i++) {
        for(int j=0; j<c; j++) {
            cin >> graph(i)(j);
        }
    }
    
    for(int i=0; i<r; i++) {
        for(int j=0; j<c; j++) {
            sheep = 0;
            wolf = 0;
            if(visited(i)(j) == 0 && graph(i)(j) != '#') dfs(i ,j);
            
            if(sheep > wolf) sheep_ans += sheep;
            else if(sheep <= wolf) wolf_ans += wolf;
        }
    }
    cout << sheep_ans << " " << wolf_ans << "\n";
    
    return 0;
}