본문 바로가기
알고리즘/BFS

3184 양

by tryotto 2020. 1. 20.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdio.h>
#include <utility>
#include <queue>
 
using namespace std;
 
char arr[255][255= { 0 };
int chk[255][255= { 0 };
 
int lamb = 0, wolf = 0, row, col;
 
void bfs(int y, int x) {    
    queue<pair<intint>> q;
 
    int tmpLamb = 0;
    int tmpWolf = 0;
 
    q.push(make_pair(y, x));
    chk[y][x] = 1;
 
    int dx[4= { 1,-1,0,0 };
    int dy[4= { 0,0,1,-1 };
    while (!q.empty()) {
        y = q.front().first;
        x = q.front().second;
 
        q.pop();
 
        if (arr[y][x] == 'v')
            tmpWolf++;
        if (arr[y][x] == 'o')
            tmpLamb++;
 
        for (int i = 0; i < 4; i++) {
            int yy = y + dy[i];
            int xx = x + dx[i];
 
            if (xx <= 0 || xx > col || yy <= 0 || y > row)
                continue;
            if (chk[yy][xx] == 1 || arr[yy][xx] == '#')
                continue;
 
            chk[yy][xx] = 1;
            q.push(make_pair(yy, xx));
        }
    }
 
    if (tmpLamb > tmpWolf) 
        lamb += tmpLamb;
    else 
        wolf += tmpWolf;
}
 
int main() {
    scanf("%d %d"&row, &col);
 
    for (int i = 1; i <= row; i++) {
        char tmp[255];
        scanf("%s"&tmp);
 
        for (int j = 1; j <= col; j++) {
            arr[i][j] = tmp[j - 1];
        }
    }
 
    for (int i = 1; i <= row; i++) {
        for (int j = 1; j <= col; j++) {
            if (arr[i][j] != '#' && chk[i][j] == 0) {                
                bfs(i, j);
            }
        }
    }
    printf("%d %d", lamb, wolf);
}
cs

DFS로 풀어야된다고 생각했는데, BFS로 풀어도 충분히 가능했다.
어렵지 않았다.


'알고리즘 > BFS' 카테고리의 다른 글

9205 맥주 마시면서 걸어가기  (0) 2020.01.21
1953 팀배분  (0) 2020.01.20
2251 물통  (0) 2020.01.20
12761 돌다리  (0) 2020.01.20
9372 상근이의 여행  (0) 2020.01.20