알고리즘/백준

14502 - 연구소[G4]

블랑v 2023. 12. 8. 22:22

문제

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

 

14502번: 연구소

인체에 치명적인 바이러스를 연구하던 연구소에서 바이러스가 유출되었다. 다행히 바이러스는 아직 퍼지지 않았고, 바이러스의 확산을 막기 위해서 연구소에 벽을 세우려고 한다. 연구소는 크

www.acmicpc.net

 

인체에 치명적인 바이러스를 연구하던 연구소에서 바이러스가 유출되었다. 다행히 바이러스는 아직 퍼지지 않았고, 바이러스의 확산을 막기 위해서 연구소에 벽을 세우려고 한다.

연구소는 크기가 N×M인 직사각형으로 나타낼 수 있으며, 직사각형은 1×1 크기의 정사각형으로 나누어져 있다. 연구소는 빈 칸, 벽으로 이루어져 있으며, 벽은 칸 하나를 가득 차지한다. 

일부 칸은 바이러스가 존재하며, 이 바이러스는 상하좌우로 인접한 빈 칸으로 모두 퍼져나갈 수 있다. 새로 세울 수 있는 벽의 개수는 3개이며, 꼭 3개를 세워야 한다.

예를 들어, 아래와 같이 연구소가 생긴 경우를 살펴보자.

2 0 0 0 1 1 0
0 0 1 0 1 2 0
0 1 1 0 1 0 0
0 1 0 0 0 0 0
0 0 0 0 0 1 1
0 1 0 0 0 0 0
0 1 0 0 0 0 0

이때, 0은 빈 칸, 1은 벽, 2는 바이러스가 있는 곳이다. 아무런 벽을 세우지 않는다면, 바이러스는 모든 빈 칸으로 퍼져나갈 수 있다.

2행 1열, 1행 2열, 4행 6열에 벽을 세운다면 지도의 모양은 아래와 같아지게 된다.

2 1 0 0 1 1 0
1 0 1 0 1 2 0
0 1 1 0 1 0 0
0 1 0 0 0 1 0
0 0 0 0 0 1 1
0 1 0 0 0 0 0
0 1 0 0 0 0 0

바이러스가 퍼진 뒤의 모습은 아래와 같아진다.

2 1 0 0 1 1 2
1 0 1 0 1 2 2
0 1 1 0 1 2 2
0 1 0 0 0 1 2
0 0 0 0 0 1 1
0 1 0 0 0 0 0
0 1 0 0 0 0 0

벽을 3개 세운 뒤, 바이러스가 퍼질 수 없는 곳을 안전 영역이라고 한다. 위의 지도에서 안전 영역의 크기는 27이다.

연구소의 지도가 주어졌을 때 얻을 수 있는 안전 영역 크기의 최댓값을 구하는 프로그램을 작성하시오.

 

풀이

조합 경우의 수 + BFS를 사용하는 문제.

하단 코드에 적용하지는 않았지만, 풀이 후 느낀 점이 '0 = 안전 지대' 를 전부 계산 후 카운팅하는 게 아니라,

바이러스(2)가 전파될때마다 최대 수에서 -1 해나가는 방식으로 했으면 더욱 효율적으로 짰을 수도 있을 것 같다.

최대 개수보다 아래로 떨어지면 바로 break 하면 되니까.. 다음부터는 이런 방식으로 짜봐야 할 것 같다.

코드

 

import java.util.*;
import java.io.*;
class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    
    static final int[] DR = {0, -1, 0, 1};
    static final int[] DC = {-1, 0, 1, 0};
    
    static final int COUNT = 3;
    static int N, M, res;
    static int[] number;
    static int map[][], tempMap[][];
    public static void main(String[] args) throws Exception {
    	List<Pos> emptyPos = setting(); //빈 공간 리스트
    	number = new int[COUNT]; //조합 결과 담을 배열
    	comb(0, 0, emptyPos, emptyPos.size()); //메인 로직
    	
    	System.out.println(res);
	}
    
    public static void solve() {
	
    	//바이러스(2) 찾아서 해당 좌표에서 전파 진행
    	Queue<Pos> startQ = new ArrayDeque<>();
    	for(int i = 0; i < N; i++) {
    		for(int j = 0; j < M; j++) {
    			if(tempMap[i][j] == 2) startQ.add(new Pos(i, j));
    		}
    	}
    	
    	//전파 로직
    	while(!startQ.isEmpty()) {
    		spread(startQ.poll());
    	}

    	//안전장소 체크
    	int nowRes = 0;
    	for(int i = 0; i < N; i++) {
    		for(int j = 0; j < M; j++) {
    			if(tempMap[i][j] == 0) nowRes++;
    		}
    	}

    	res = Math.max(res, nowRes);
    }
    
    public static void spread(Pos virus) {
    	Queue<Pos> bfsQ = new ArrayDeque<>();
    	boolean[][] visit = new boolean[N][M];
    	
    	bfsQ.add(virus);
    	while(!bfsQ.isEmpty()) {
    		Pos now = bfsQ.poll();
    		int r = now.r;
    		int c = now.c;
    		if(visit[r][c]) continue;
    		visit[r][c] = true;

    		tempMap[r][c] = 2;

    		for(int i = 0; i < 4; i++) {
    			int nr = r + DR[i];
    			int nc = c + DC[i];
    			if(cantGo(nr, nc) || visit[nr][nc] || tempMap[nr][nc] != 0) continue;
    			bfsQ.add(new Pos(nr, nc));
    		}
    	}
    }
    
    public static void comb(int cnt, int start, List<Pos> emptyPos, int max) {
    	if(cnt == COUNT) {
    		tempMap = new int[N][M];
    		//기존 맵 복제
        	for(int i = 0; i < N; i++) {
        		for(int j = 0; j < M; j++) {
        			tempMap[i][j] = map[i][j];
        		}
        	}

    		//벽 3개 세우기
    		for(int i = 0; i < COUNT; i++) {
    			Pos now = emptyPos.get(number[i]); 
    			tempMap[now.r][now.c] = 1; //벽 세우기
    		}
    		solve(); //메인 로직
    		return;
    	}
    	
    	for(int i = start; i < max; i++) {
    		number[cnt] = i;
    		comb(cnt + 1, i + 1, emptyPos, max);
    	}
    }
    
    public static List<Pos> setting() throws Exception {
    	List<Pos> emptyPos = new ArrayList<>();
    	StringTokenizer st = new StringTokenizer(br.readLine());
    	N = Integer.parseInt(st.nextToken());
    	M = Integer.parseInt(st.nextToken());
    	map = new int[N][M];
    	
    	for(int i = 0; i < N; i++) {
    		st = new StringTokenizer(br.readLine());
    		for(int j = 0; j < M; j++) {
    			int now = Integer.parseInt(st.nextToken());
    			map[i][j] = now;
    			if(now == 0) emptyPos.add(new Pos(i, j));
    		}
    	}
    	
    	return emptyPos; //빈 공간
    }
    
    
    
    
    public static boolean cantGo(int r, int c) {
    	if(r < 0 || c < 0 || r >= N || c >= M) return true;
    	return false;
    }
}

class Pos {
	int r, c;
	public Pos(int r, int c) {
		this.r = r;
		this.c = c;
	}
}