https://www.acmicpc.net/problem/7576
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토
www.acmicpc.net
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int M, N, answer = 0;
static int[][] map;
static int[] dr = { -1, 1, 0, 0 };
static int[] dc = { 0, 0, -1, 1 };
static Queue<Pos> tomatoList = new LinkedList<>();
// 토마토 위치 정보
static class Pos {
int r, c;
public Pos(int r, int c) {
this.r = r;
this.c = c;
}
}
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 입력 받기
map[i][j] = Integer.parseInt(st.nextToken());
// 익은 토마토인 경우 tomatoList에 추가
if (map[i][j] == 1) {
tomatoList.offer(new Pos(i, j));
}
}
}
// 토마토 익히기
bfs();
// 날짜 구하기
answer = getDate() == -1 ? -1 : getDate();
System.out.println(answer);
}
private static void bfs() {
while (!tomatoList.isEmpty()) {
Pos curr = tomatoList.poll();
for (int dir = 0; dir < 4; dir++) {
int nr = curr.r + dr[dir];
int nc = curr.c + dc[dir];
// 경계 벗어나지 않았고 익지 않은 토마토라면
// 현재 위치 + 1(: 날짜 구하기 위해) 해주고 tomatoList에 추가
if ((nr >= 0 && nr < N && nc >= 0 && nc < M) && map[nr][nc] == 0) {
map[nr][nc] = map[curr.r][curr.c] + 1;
tomatoList.offer(new Pos(nr, nc));
}
}
}
}
private static int getDate() {
int max = -1;
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]);
}
}
return max - 1;
}
}
'Baekjoon Online Judge > Java' 카테고리의 다른 글
[Baekjoon Online Judge] 3055 - 탈출 / Java (0) | 2021.09.28 |
---|---|
[Baekjoon Online Judge] 11581 - 구호물자 / Java (0) | 2021.09.25 |
[Baekjoon Online Judge] 2210 - 숫자판 점프 / Java (0) | 2021.09.20 |
[Baekjoon Online Judge] 2636 - 치즈 / Java (0) | 2021.09.15 |
[Baekjoon Online Judge] 1197 - 최소 스패닝 트리 / Java (0) | 2021.09.07 |