토마토(BFS 활용)

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

class Tomato{
	int x, y;
	public Tomato(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

public class Main {
	
	static int[][] box;
	static int[][] day;
	
	static int[] dx = {1, -1, 0, 0};
	static int[] dy = {0, 0, 1, -1};
	
	static int n, m;
	
	static Queue<Tomato> queue = new LinkedList<>();
	
	public void BFS() {
		while(!queue.isEmpty()) {
			Tomato tomato = queue.poll();
			for(int i=0; i<4; i++) {
				int nx = tomato.x + dx[i];
				int ny = tomato.y + dy[i];
				
				if(ny>=0 && ny<m && nx>=0 && nx<n && box[nx][ny]==0) {
					box[nx][ny] = 1;
					queue.offer(new Tomato(nx, ny));
					day[nx][ny] = day[tomato.x][tomato.y] + 1; 
				}
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		
		m = kb.nextInt();
		n = kb.nextInt();
		box = new int[n][m];
		day = new int[n][m];
		
		for(int i=0; i<n; i++) {
			for(int j=0; j<m; j++) {
				box[i][j] = kb.nextInt();
				if(box[i][j] == 1) queue.offer(new Tomato(i, j));
			}
		}
		
		T.BFS();
		
		boolean flag = true;
		int answer = Integer.MIN_VALUE;
		
		for(int i=0; i<n; i++) {
			for(int j=0; j<m; j++) {
				if(box[i][j] == 0) flag = false;
			}
		}
		
		if(flag == true) {
			for(int i=0; i<n; i++) {
				for(int j=0; j<m; j++) {
					answer = Math.max(answer, day[i][j]);
				}
			}
		}
		else answer = -1;
		
		System.out.println(answer);
	}

}

'Solved > 코딩테스트' 카테고리의 다른 글

뮤직비디오(결정알고리즘)  (0) 2023.04.03
섬나라 아일랜드 (BFS, DFS)  (0) 2023.03.30
후위연산식 문제 (Stack)  (0) 2023.03.18
임시반장 정하기 문제  (0) 2023.03.17
Least Recently Used  (0) 2023.03.14