CS/Algorithm

[백준 : 7576] 토마토 - JAVA

yujindonut 2021. 5. 23. 20:05
728x90

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

class Dot{
	int x, y;
	public Dot(int x, int y) {
		this.x = x;
		this.y = y;
	}
}
public class Main {
	static int map[][]; // 2차원 미로 배열
	static int n,m;
	static int[] dx = {-1,0,1,0};
	static int[] dy = {0,1,0,-1};
	
	public static int bfs() { //BFS메소드
		
		Queue<Dot> q = new LinkedList<>();
		
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < m; j++) {
				if(map[i][j] == 1)
					q.offer(new Dot(i,j));
			}
		}

		while(!q.isEmpty()) {
			
			Dot dot = q.poll();
			int qx = dot.x;
			int qy = dot.y;
			
			//상하좌우 4방향 노드 범위 벗어나는지 탐색
			for(int i = 0; i < 4; i++) {
				int x = qx + dx[i];
				int y = qy + dy[i];
				
				if(0 <= x && x < n && 0 <= y && y < m) {
					if(map[x][y] == 0){//안익은 토마토라면{
						q.offer(new Dot(x,y));
						//추가한 노드까지의 거리 = 현재 노드 까지의 거리 + 1
						map[x][y] = map[qx][qy] + 1;
					}
				}
			}
		}
		int max = 0;
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < m; j++) {
				if(map[i][j] == 0)//안익은게 있다면
					return -1;
				max = Math.max(max, map[i][j]);
			}
		}
		//토마토가 모두 익은 상태일 경우 
		if(max == 1)
			return 0;
		//걸린 일수
		else {
			return max - 1;			
		}

	}
	public static void main(String[] args) throws Exception {

		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());
		
	}
	
}
728x90