슈콩

[BOJ] 17142 연구소3 본문

Algorithms/Baekjoon

[BOJ] 17142 연구소3

shukong 2025. 12. 7. 23:46

 

 

[문제]

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

 

 

[소스 코드]

import java.io.*;
import java.util.*;

public class Main {
	static int n,m,result = Integer.MAX_VALUE;
	static int[][] lab,copy;
	static boolean[] select;
	static List<int[]> virus;
	static int[] dr = {-1,1,0,0};
	static int[] dc = {0,0,-1,1};
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		n = Integer.parseInt(st.nextToken());
		m = Integer.parseInt(st.nextToken());
		lab = new int[n][n];
		virus = new ArrayList<>();
		for(int i=0;i<n;i++) {
			st = new StringTokenizer(br.readLine());
			for(int j=0;j<n;j++) {
				lab[i][j] = Integer.parseInt(st.nextToken());
				if(lab[i][j]==2) virus.add(new int[] {i,j});
			}
		}
		select = new boolean[virus.size()];
		combi(0,0);
		System.out.println(result==Integer.MAX_VALUE ? -1 : result);
	}
	private static void combi(int idx,int cnt) {
		if(cnt==m) {
			bfs();
			return;
		}
		for(int i=idx;i<virus.size();i++) {
			if(!select[i]) {
				select[i] = true;
				combi(i+1,cnt+1);
				select[i] = false;
			}
		}
	}
	private static void bfs() {
		Queue<int[]> q = new LinkedList<>();
		copy = new int[n][n];
		boolean[][] visit = new boolean[n][n];
		for(int i=0;i<virus.size();i++) {
			if(select[i]) {
				int[] v = virus.get(i);
				q.offer(new int[] {v[0],v[1]});
				visit[v[0]][v[1]] = true;
			}
		}
		int time = 0;
		while(!q.isEmpty()) {
			int[] curr = q.poll();
			for(int d=0;d<4;d++) {
				int nr = curr[0] + dr[d];
				int nc = curr[1] + dc[d];
				if(nr<0 || nr>=n || nc<0 || nc>=n || visit[nr][nc] || lab[nr][nc]==1) continue;
				q.offer(new int[] {nr,nc});
				visit[nr][nc] = true;
				copy[nr][nc] = copy[curr[0]][curr[1]] + 1;
				if(lab[nr][nc]==0) time = Math.max(time, copy[nr][nc]);
			}
		}
		if(possible()) {
			result = Math.min(result, time);
		}
	}
	private static boolean possible() {
		for(int i=0;i<n;i++) {
			for(int j=0;j<n;j++) {
				if(lab[i][j]==0 && copy[i][j]==0) return false;
			}
		}
		return true;
	}
}

 

바이러스 지정되지 않은 자리도 시간 추가 : copy에 저장(time) -> q에 시간 저장 불가 !

'Algorithms > Baekjoon' 카테고리의 다른 글

[BOJ] 17837 새로운 게임 2  (0) 2025.12.09
[BOJ] 17779 게리멘더링 2  (0) 2025.12.08
[BOJ] 17140 이차원 배열과 연산  (0) 2025.12.07
[BOJ] 17143 낚시왕  (0) 2025.12.06
[BOJ] 17144 미세먼지 안녕!  (0) 2025.12.06