본문 바로가기
알고리즘/백준

백준 7576 토마토 (자바)

by 김어찐 2021. 9. 24.
728x90
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class algo_7576_김어진 {
	static int N;
	static int M;
	static int[][] board;
	static int[] dx = {-1,0,1,0};
	static int[] dy = {0,1,0,-1};
	public static void main(String[] args) throws Exception {
		System.setIn(new FileInputStream("input.txt"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine()," ");
		M = Integer.parseInt(st.nextToken());
		N = Integer.parseInt(st.nextToken());
		int answer = 0;
		board = new int[N][M];
		for (int i = 0; i < N; i++) {
			board[i]= Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
		}


		Queue<tomato> q = new LinkedList<tomato>(); 
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				if(board[i][j]==1) {
					q.add(new tomato(i,j,0));	
				}
			}
		}
		while(!q.isEmpty()) {
			tomato pos = q.poll();
			int x = pos.x;
			int y = pos.y;
			int time  = pos.time;
			for (int z = 0; z < 4; z++) {
				int nx = x+dx[z];
				int ny = y+dy[z];
				if(nx>=0 && nx < N && ny>=0 && ny <M && board[nx][ny]==0) {
					board[nx][ny]=1;
					q.add(new tomato(nx,ny,time+1));
					answer = Math.max(answer, time+1);
				}
			}
		}
		int cnt = check();
		if(cnt>0) {
			System.out.println(-1);
			return;
		}
		System.out.println(answer);
	}
	private static int check() {
		int cnt = 0;
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				if(board[i][j]==0) {
					cnt++;
				}
			}
		}
		return cnt;
	}
}
class tomato{
	
	public tomato(int x, int y, int time) {
		super();
		this.x = x;
		this.y = y;
		this.time = time;
	}
	int x;
	int y;
	int time;
	
}
728x90