알고리즘/백준

[백준 22352] 항체 인식 C++

겜도리도리 2021. 9. 3. 23:48
반응형

문제

백준 22352

 

22352번: 항체 인식

첫 번째 줄에는 SP 촬영 결과의 크기를 의미하는 두 정수 $N$과 $M$이 주어진다. ($1 \le N, M \le 30$) 이는 촬영 결과가 세로로 $N$칸, 가로로 $M$칸 크기의 격자라는 것을 의미한다. 다음 $N$개의 줄에는

www.acmicpc.net

풀이

전형적인 bfs, dfs 문제입니다.

투약 전과 투약 후의 상태를 입력받습니다.

루프를 돌면서, 전과 후의 상태가 다르면 그 지점부터 bfs를 해줍니다.

bfs 이후에도 전과 후가 다르다면, 백신이 아니므로 NO를 출력합니다.

같다면 YES를 출력합니다.

소스 코드

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
 
int premap[30][30];
int nextmap[30][30];
int dx[] = { 00-11 };
int dy[] = { 1-100 };
bool ispossible = true;
bool visited[30][30];
int n, m;
 
void bfs(int a, int b, int num, int targetnum)
{
    if (visited[a][b])
        return;
    visited[a][b] = true;
    queue<pair<intint>> q;
    q.push(make_pair(a, b));
    while (!q.empty())
    {
        int x = q.front().second;
        int y = q.front().first;
        q.pop();
        premap[y][x] = targetnum;
        for (int i = 0; i < 4; i++)
        {
            int nx = x + dx[i];
            int ny = y + dy[i];
            if (nx >= 0 && nx < m && ny >= 0 && ny < n)
            {
                if (!visited[ny][nx] && premap[ny][nx] == num)
                {
                    visited[ny][nx] = true;
                    q.push(make_pair(ny, nx));
                }
 
            }
        }
    }
    // bfs 실행 후 같은 지 검사
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            if (premap[i][j] != nextmap[i][j])
                ispossible = false;
        }
    }
}
 
int main()
{
    cin >> n >> m;
    // 투약 전 입력
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cin >> premap[i][j];
        }
    }
    // 투약 후 입력
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cin >> nextmap[i][j];
        }
    }
    // 루프 돌면서 확인
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            // 투약 전 / 후 다르면 bfs
            if (premap[i][j] != nextmap[i][j])
            {
                bfs(i, j, premap[i][j], nextmap[i][j]);
            }
        }
    }
    if (ispossible)
        cout << "YES";
    else
        cout << "NO";
    return 0;
}
cs
반응형

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

[백준 2606] 바이러스 (C++)  (0) 2021.09.04
[백준 9095] 1, 2, 3 더하기 (C++)  (0) 2021.09.04
[백준 20364] 부동산 다툼 C++  (0) 2021.09.01
[백준 3079] 입국심사 (C++)  (0) 2021.08.30
[백준 12865] 평범한 배낭 (C++)  (0) 2021.08.29