[알고리즘] 백준 14502

dlwl98·2022년 5월 20일
0

알고리즘공부

목록 보기
12/34
post-thumbnail

백준 14502번 연구소

해결 과정 요약

빈칸중에서 벽을 세울 3곳을 정해야 하므로 next_permutation을 이용해 combination을 만들어준다.
벽을 세운 뒤 바이러스의 위치마다 dfs를 해주고 남은 빈칸의 개수를 잘 세어본다.
ret값을 최신화 시켜주고 세워주었던 벽을 허물어준 뒤, visited배열을 0으로 초기화시킨다.
벽을 세우고 허무는 작업을 모든 조합의 경우의 수만큼 해준다.

풀이

#include <bits/stdc++.h>
using namespace std;

int N,M,ret;
int a[8][8];
int visited[8][8];
vector<pair<int,int>> v;
vector<int> ind;
int dy[4] = {-1, 0, 1, 0};
int dx[4] = {0, 1, 0, -1};

void dfs(int y, int x){
    visited[y][x] = 1;
    for(int i=0; i<4; i++){
        int ny = y + dy[i];
        int nx = x + dx[i];
        if(ny < 0 || nx < 0 || ny >= N || nx >= M) continue;
        if(visited[ny][nx] || a[ny][nx] == 1) continue;
        dfs(ny, nx);
    }
}

int cnt(){
    int n = 0;
    for(int i=0; i<N; i++){
        for(int j=0; j<M; j++){
            if(!visited[i][j] && !a[i][j])
                n++;
        }
    }
    return n;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);

    cin >> N >> M;
    for(int i=0; i<N; i++){
        for(int j=0; j<M; j++){
            cin >> a[i][j];
            if(!a[i][j]) v.push_back({i, j});
        }
    }
    for(int i=0; i<3; i++) ind.push_back(0);
    for(int i=3; i<v.size(); i++) ind.push_back(1);
    
    do{
        for(int i=0; i<v.size(); i++)
            if(ind[i] == 0) a[v[i].first][v[i].second] = 1;
        
        for(int i=0; i<N; i++){
            for(int j=0; j<M; j++){
                if(visited[i][j] == 0 &&a[i][j] == 2)
                    dfs(i,j);
            }
        }
        ret = max(ret, cnt());
        
        for(int i=0; i<v.size(); i++)
            if(ind[i] == 0) a[v[i].first][v[i].second] = 0;
        fill(&visited[0][0], &visited[0][0] + 64, 0);
        
    }while(next_permutation(ind.begin(), ind.end()));
    
    cout << ret;
    return 0;
}

코멘트

DFS문제이긴 하지만 모든 경우의 수를 다 따져봐야 하는 문제였다.
너무 노가다느낌..

0개의 댓글