14502 연구소 Java

문제 🌐

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

연구소는 크기가 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이다.

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

입력

첫째 줄에 지도의 세로 크기 N과 가로 크기 M이 주어진다. (3 ≤ N, M ≤ 8)

둘째 줄부터 N개의 줄에 지도의 모양이 주어진다. 0은 빈 칸, 1은 벽, 2는 바이러스가 있는 위치이다. 2의 개수는 2보다 크거나 같고, 10보다 작거나 같은 자연수이다.

빈 칸의 개수는 3개 이상이다.

출력

첫째 줄에 얻을 수 있는 안전 영역의 최대 크기를 출력한다.

접근 방법

나에게 고통을 선사한 연구소 시리즈의 풀이를 올려 보도록 하겠습니다. 때는 2023년 9월, 스터디에서 연구소 3 문제를 숙제로 받은 저는 9n% 에서 정답을 받지 못하고 외면하고 있었으나, 최근 A형에 대비하여 그래프 탐색 문제를 정복하며 세 연구소 모두를 박살낼 수 있었습니다.

성장했다…!

연구소의 빈 공간에 벽을 세워 바이러스가 퍼지는 것을 막은 후 바이러스가 퍼지지 않은 구역의 최대 넓이를 구하는 문제입니다.

  1. 입력 시 빈 공간의 크기를 세고, Node 클래스를 만들어 빈 공간의 좌표를 ArrayList에 담는다.
  2. 벽을 세울 세 지점을 조합으로 구한다.
  3. 벽을 세우고 바이러스를 퍼뜨린 후, 빈 공간의 개수를 하나씩 줄여 나간다.
  4. 바이러스가 다 퍼지면, 빈 공간의 크기를 최대값 연산으로 갱신한다.

입력받고 조합 구하기

빈 공간의 개수를 체크하고, 조합을 구합니다.

지금 생각해 보니 입력받을 때 바이러스의 위치도 ArrayList에 담아뒀으면 좋았을 것 같습니다!!

for (int i=0; i<N; i++) {
	for (int j=0; j<M; j++) {
		int temp = sc.nextInt();
		if (temp == 0) {
			space.add(new Node(i, j));
		}
		map[i][j] = temp;
	}
}

empty = space.size();
int[] result = new int[3];
boolean[] chk = new boolean[empty];
combination(0, 0, result, chk);
System.out.println(answer);

백트래킹을 이용해 조합을 구했고, idx == 3 이 되었을 때 배열을 복사하여 bfs 메소드로 넘깁니다.

public static void combination(int idx, int start, int[] result, boolean[] chk) {
	if (idx==3) {
		int[] temp = Arrays.copyOf(result, 3);
		bfs(temp);
		return;
	}
	for (int i=start; i<empty; i++) {
		if (!chk[i]) {
			chk[i] = true;
			result[idx] = i;
			combination(idx+1, i+1, result, chk);
			chk[i] = false;
		}
	}
}

바이러스 퍼뜨리기

모든 경우에 대해 바이러스를 퍼뜨려 봅니다. 조합의 인덱스에 해당하는 빈 공간의 좌표를 가져와서 벽을 세우고, 방문 처리를 해줍니다. (벽으로는 이동할 수 없기 때문에)

그리고 맵을 탐색하면서 바이러스를 넣어주고, (이걸 입력받을 때 ArrayList에 담아두고 그대로 꺼내서 넣었어도 됐다. 하지만 벽인 경우에도 깊은 복사를 통해 체크해 줬어야 하는 부분이니 언제 하든 중요하지 않아 보인다!)

이동할 수 있는 곳 모두에 바이러스를 퍼뜨리고 남은 빈 공간의 개수가 나오면, Math.max로 answer에 초기화한다.

public static void bfs(int[] temp) {
	int cnt = empty - 3;
	boolean[][] visited = new boolean[N][M];
	for (int i=0; i<3; i++) {
		Node now = space.get(temp[i]);
		visited[now.r][now.c] = true; 
	}
	
	Queue<Node> q = new LinkedList<>();
	
	for (int i=0; i<N; i++) {
		for (int j=0; j<M; j++) {
			if (map[i][j] == 2) {
				q.add(new Node(i, j));
				visited[i][j] = true;
			} 
			if (map[i][j] == 1) visited[i][j] = true;
		}
	}
	
	while(!q.isEmpty()) {
		Node curr = q.poll();
		int r = curr.r;
		int c = curr.c;
		for (int d=0; d<4; d++) {
			int nr = r+dr[d];
			int nc = c+dc[d];
			if (isValid(nr, nc) && !visited[nr][nc] && map[nr][nc] == 0) {
				q.add(new Node(nr, nc));
				visited[nr][nc] = true;
				// 바이러스를 퍼뜨렸으니 빈 공간의 개수 -1
				cnt--;
			}
			
		}
		
	}
	answer = Math.max(answer, cnt);
	
}

Full Solution

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
	static class Node {
		int r;
		int c;
		public Node(int r, int c) {
			super();
			this.r = r;
			this.c = c;
		}
		
	}
	
	static int N;
	static int M;
	static int[][] map;
	static int answer;
	static int empty;
	static int[] dr = {0, 0, -1, 1};
	static int[] dc = {-1, 1, 0, 0};
	static ArrayList<Node> space = new ArrayList<>();
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		M = sc.nextInt();
		answer = 0;
		empty = 0;
		map = new int[N][M];
		for (int i=0; i<N; i++) {
			for (int j=0; j<M; j++) {
				int temp = sc.nextInt();
				if (temp == 0) {
					space.add(new Node(i, j));
					empty++;
				}
				map[i][j] = temp;
			}
		}
		
		empty = space.size();
		int[] result = new int[3];
		boolean[] chk = new boolean[empty];
		combination(0, 0, result, chk);
		System.out.println(answer);
		
	}
	
	public static void combination(int idx, int start, int[] result, boolean[] chk) {
		if (idx==3) {
			int[] temp = Arrays.copyOf(result, 3);
			bfs(temp);
			return;
		}
		for (int i=start; i<empty; i++) {
			if (!chk[i]) {
				chk[i] = true;
				result[idx] = i;
				combination(idx+1, i+1, result, chk);
				chk[i] = false;
			}
		}
	}
	
	
	public static void bfs(int[] temp) {
		int cnt = empty - 3;
		boolean[][] visited = new boolean[N][M];
		for (int i=0; i<3; i++) {
			Node now = space.get(temp[i]);
			visited[now.r][now.c] = true; 
		}
		
		Queue<Node> q = new LinkedList<>();
		
		for (int i=0; i<N; i++) {
			for (int j=0; j<M; j++) {
				if (map[i][j] == 2) {
					q.add(new Node(i, j));
					visited[i][j] = true;
				} 
				if (map[i][j] == 1) visited[i][j] = true;
			}
		}
		
		while(!q.isEmpty()) {
			Node curr = q.poll();
			int r = curr.r;
			int c = curr.c;
			for (int d=0; d<4; d++) {
				int nr = r+dr[d];
				int nc = c+dc[d];
				if (isValid(nr, nc) && !visited[nr][nc] && map[nr][nc] == 0) {
					q.add(new Node(nr, nc));
					visited[nr][nc] = true;
					cnt--;
				}
				
			}
			
		}
		answer = Math.max(answer, cnt);
		
	}
	
	
	public static boolean isValid(int r, int c) {
		if (r < 0 || r >= N || c<0 || c>=M) return false;
		return true;
	}

}