백준/그래프 이론

18405 경쟁적 전염

have a good time 2024. 6. 22. 23:17
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;


class Position{
	
	int x;
	int y;
	int virus;
	
	Position(int x, int y, int virus) {
		
		this.x = x;
		this.y = y;
		this.virus = virus;
	}
}

public class Main {	
	
	static int map[][];	
	static int N;
	static int K;	
	static Queue<Position> q;
	static int S;
	
	
	public static void main(String[] args) throws IOException {		
	
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine(), " ");
		N = Integer.parseInt(st.nextToken());
		K = Integer.parseInt(st.nextToken());
		map = new int [N+1][N+1];
		q =  new LinkedList<>();
		List<Position> list = new ArrayList<>();
		
		for(int i=1; i<=N; i++) {
			st = new StringTokenizer(br.readLine(), " ");
			for(int j= 1; j<=N; j++) {
				
				int value = Integer.parseInt(st.nextToken());
				map[i][j] = value;
				
				// 바이러스인 경우
				if(value != 0) {
					list.add(new Position(i,j, value));
				}				
			}
		}	
		
		// 바이러스 번호가 작을수록 앞으로 위치
        Collections.sort(list, new Comparator<Position>() {
            @Override
            public int compare(Position p1, Position p2) {
                return p1.virus - p2.virus;
            }
        });

		
        for(int i=0; i<list.size(); i++) {
        	Position p = list.get(i);
        	q.add(new Position(p.x,p.y,p.virus));
        }
		
		st = new StringTokenizer(br.readLine(), " ");		
		S =  Integer.parseInt(st.nextToken());
		int X =  Integer.parseInt(st.nextToken());
		int Y =  Integer.parseInt(st.nextToken());
		
		bfs();		
		System.out.println(map[X][Y]);	
		
	}
	
	
	
	public static void bfs() {			
	
		int time = 1;		
		
		int virusType = q.peek().virus;
	
		// time(시간)은 같은 종류의 바이러스가 큐에서 다 나온 뒤 증가하므로
		// time < S(문제에서 주어진 시간 제한) * K(바이러스 종류 개수) 때까지  
		while(!q.isEmpty() && time<S*K) {	
					
			Position p = q.poll();	
			
			
			// time(시간)은 같은 종류의 바이러스가 큐에서 다 나온 뒤 증가
			if(p.virus != virusType) {
				time++;
				virusType = p.virus;
			}
			
	
			int dx [] = {-1,1,0,0};
			int dy [] = {0,0,-1,1};
	
	
				for(int i=0;i<4; i++) {
					
					int nx = p.x + dx[i];
					int ny = p.y + dy[i];		
					
					// 바이러스가 이동할 수 있으면
					if(nx>0 && nx<=N && ny>0 && ny<=N && map[nx][ny]==0) {
							
							// 바이러스 이동시킴
							map[nx][ny] = p.virus;					
							q.add(new Position(nx, ny, p.virus));
						
					}
				}					
				
		}
		
	}
}