본문 바로가기
알고리즘

[알고리즘] c++ cpp 연구소시리즈 (연구소3)

by keel_im 2020. 10. 5.
반응형

포인트

1. bfs 를 잘 할 수 있는가?

2. 활성 비활성을 잘 구분할 수 있는가?

 

#include <iostream>
#include <queue>
#include <vector>
#include<cstring>
#include <algorithm>
#include <tuple>

using namespace std;
#define MAX 50
#define VIRUS_MAX 10

int map[MAX][MAX];
int dist[MAX][MAX];
int n, m;
int virusCount = 0;
int answer = 987654321;
bool virusVisited[VIRUS_MAX];
vector<pair<int, int>> virus;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};

void bfs(int size) {
    queue<pair<int, int>> q;
    for (int i = 0; i < size; i++) {
        if (virusVisited[i]) {
            q.push(make_pair(virus[i].first, virus[i].second));
            dist[virus[i].first][virus[i].second] = 0;
        }
    }

    int check = 0;
    int time = 0;
    while (!q.empty()) {
        int x, y;
        tie(x, y) = q.front();
        q.pop();

        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue; // 범위 체크
            if (map[nx][ny] == 1 || dist[nx][ny] != -1) continue; // 조건 넣기
            q.push(make_pair(nx, ny));
            dist[nx][ny] = dist[x][y] + 1;

            if (map[nx][ny] == 0) {
                check++;
                time = dist[nx][ny];
            }
        }
    }

    if (check == virusCount)
        answer = min(answer, time);
}

void go(int index, int cnt, int size) {
    if (cnt == m) {
        memset(dist, -1, sizeof(dist));
        bfs(size);
        return;
    }

    if (index >= size) return;

    virusVisited[index] = 1;
    go(index + 1, cnt + 1, size);
    virusVisited[index] = 0;

    go(index + 1, cnt, size);
}

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] == 2) // 바이러스
                virus.push_back(make_pair(i, j));
            if (map[i][j] == 0) //숫자를 센다.
                virusCount++;
        }
    }

    go(0, 0, virus.size());
    if (answer == 987654321) cout << -1 << '\n';
    else cout << answer << '\n';

}
반응형

댓글