7576_토마토

고장난·2022년 2월 25일
0

백준

목록 보기
1/1
package 문제;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

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


public class bj7576 {
	static int[][] map ;
	static int[] dx= { -1 , 1 , 0 , 0 };
	static int[] dy= { 0 , 0 , -1 , 1 };
	static int M,N;
	public static void main(String[] args) throws IOException {
		BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st= new StringTokenizer(br.readLine());
		
		M = Integer.parseInt(st.nextToken());
		N = Integer.parseInt(st.nextToken());
		map= new int[N][M];
		for(int i =0; i<N;i++) {
			st= new StringTokenizer(br.readLine());
			for(int j=0;j<M;j++) {
				map[i][j]=Integer.parseInt(st.nextToken());
				}
			}
		System.out.println(bfs());
		
		
	}
	
	public static int bfs(){
		Queue<tomato> queue = new LinkedList<tomato>();
		for(int i =0; i<N;i++) {
			for(int j=0;j<M;j++) {
				if(map[i][j]==1) {
					queue.add(new tomato(i,j));
				}
			}
		}
		
		while(!queue.isEmpty()) {
			tomato t= queue.remove();
			
			for(int i=0;i<4;i++) {
				int nx=t.x+dx[i];
				int ny=t.y+dy[i];
				if(nx<0||ny<0||nx>=N||ny>=M)continue;
				
				if(map[nx][ny]==0) {
					queue.add(new tomato(nx,ny));
					map[nx][ny]=map[t.x][t.y]+1;
				}
			}
		}
		int result = 0;
		
		for(int i=0;i<N;i++) {
			for(int j =0;j<M;j++) {
				if(map[i][j]==0)
					return -1;
				result= Math.max(result, map[i][j]);
			}
		}
		if(result==1)
			return 0;
		else
			return result-1;


	}
	
}
profile
훈련중

0개의 댓글

관련 채용 정보