Gidhub BE Developer

[BOJ] 14502. 연구소

2018-10-16
goodGid

Problem

Problem URL : 연구소


[1] Answer Code (18. 10. 16)

#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#define p pair<int,int>
using namespace std;

// 동서남북
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};

int n,m;
int map[8][8];
int ans;

vector<p> virus;
vector<p> list;

bool inRange(int x, int y){
    if( x < 0 || x >= n || y < 0 || y >= m)
        return false;
    return true;
}

int cal(){
    int v[8][8] = {0,};
    queue<p> q;
    
    for(int i=0; i<n; i++){
        for(int j=0; j<m; j++){
            v[i][j] = map[i][j];
        }
    }
    
    for(int i=0; i<virus.size(); i++){
        q.push(p(virus[i].first, virus[i].second));
    }
    
    while (! q.empty()) {
        int x = q.front().first;
        int y= q.front().second;
        q.pop();
        
        for(int i=0; i<4; i++){
            int nx = x + dx[i];
            int ny = y + dy[i];
            
            if(! inRange(nx, ny)) continue;
            if(v[nx][ny] == 2) continue;
            
            if(map[nx][ny] == 1 || map[nx][ny] == 2){
                v[nx][ny] = 1;
                continue;
            }
            else if(map[nx][ny] == 0 && v[nx][ny] == 0 ){
                v[nx][ny] = 2;
                q.push(p(nx,ny));
            }
        }
    }
    
    int cnt = 0;
    for(int i=0; i<n; i++){
        for(int j=0; j<m; j++){
            if(v[i][j] == 0)
                cnt ++;
        }
    }
    
    return cnt;
}


void dfs(int idx, int p_cnt){ // p_cnt is pick count
    if(p_cnt == 3){
        int res = cal();
        ans = ans < res ? res : ans;
        return ;
    }
    int size = (int)list.size();
    
    for(int i=idx; i<size; i++){
        int x = list[i].first;
        int y = list[i].second;
        map[x][y] = 1;
        dfs(i+1,p_cnt+1);
        map[x][y] = 0;
    }
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    
    ans = -1;

    cin >> n >> m;
    for(int i=0; i<n; i++){
        for(int j=0; j<m; j++){
            cin >> map[i][j];
            if(map[i][j] == 0)
                list.push_back(p(i,j));
            else if(map[i][j] == 2)
                virus.push_back(p(i,j));
        }
    }
    
    dfs(0,0);
    
    cout << ans << endl;
    return 0;
}

Review

  • 삼성 역량 테스트 기출 문제

  • DFS + BFS


Comments

Content