코딩공작소

[백준]연구소2 본문

알고리즘/그래프

[백준]연구소2

안잡아모찌 2019. 9. 3. 15:58

https://www.acmicpc.net/problem/17141

 

17141번: 연구소 2

인체에 치명적인 바이러스를 연구하던 연구소에 승원이가 침입했고, 바이러스를 유출하려고 한다. 승원이는 연구소의 특정 위치에 바이러스 M개를 놓을 것이고, 승원이의 신호와 동시에 바이러스는 퍼지게 된다. 연구소는 크기가 N×N인 정사각형으로 나타낼 수 있으며, 정사각형은 1×1 크기의 정사각형으로 나누어져 있다. 연구소는 빈 칸, 벽으로 이루어져 있으며, 벽은 칸 하나를 가득 차지한다. 일부 빈 칸은 바이러스를 놓을 수 있는 칸이다. 바이러스는 상하좌우로

www.acmicpc.net

연구소 시리즈 문제.. 조합으로 바이러스를 선택하면 된다. 그리고 bfs를 해줌.

전부 탐색이 됐는지 안됐는지 따지기 위해 탐색이 될 수 있는 공간을 구해서 체크해주는 것이 포인트.

 

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 <iostream>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
 
int N, M, space = 0;
int map[50][50], isV[50][50];
bool com[10];
vector<pair<intint> > birus; //M개 선택
queue <pair<intint> > q;
int ans = 1e9;
int dr[] = { 0,0,-1,1 }, dc[] = { 1,-1,0,0 };
 
int bfs() {
    int cnt = 0, time = 0;
    while (!q.empty()) {
        int r = q.front().first, c = q.front().second; q.pop();
 
        for (int i = 0; i < 4; i++) {
            int nr = r + dr[i], nc = c + dc[i];
            if (nr < 0 || nc < 0 || nr >= N || nc >= N || isV[nr][nc] != -1 || map[nr][nc] == 1continue;
            
            q.push(make_pair(nr, nc));
            isV[nr][nc] = isV[r][c] + 1;
            time = isV[nr][nc];
            cnt++;
        }
    }
 
    if (cnt == space + birus.size() - M) return time;
    return 1e9;
    //if(cnt == space+ birus.size()-M && ans > time) ans=time //이거로만 해도됨 void형.
}
 
void dfs(int s, int len) {
    if (len == M) {
        memset(isV, -1sizeof(isV));
        for (int i = 0; i < birus.size(); i++) {
            if (com[i]) { 
                q.push(make_pair(birus[i].first, birus[i].second));
                isV[birus[i].first][birus[i].second] = 0;
            }
        }
        
        int a = bfs();
        if (ans >= a) ans = a;
        return;
    }
 
    for (int i = s; i < birus.size(); i++) {
        if (!com[i]) {
            com[i] = true;
            dfs(i, len + 1);
            com[i] = false;
        }
    }
}
 
int main()
{
    cin >> N >> M;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            cin >> map[i][j];
            if (map[i][j] == 0) space++;
            if (map[i][j] == 2) birus.push_back(make_pair(i, j));
        }
    }
    
    dfs(00);
    printf("%d\n", ans == 1e9 ? -1 : ans);
    return 0;
}
cs

'알고리즘 > 그래프' 카테고리의 다른 글

[백준]단지번호붙이기  (0) 2019.09.14
섬번호매기기  (0) 2019.09.13
[SWEA]홈 방법 서비스  (0) 2019.08.27
[bfs]단계설정?  (0) 2019.08.26
[SWEA]벽돌깨기  (0) 2019.08.25