파게로그
[백준 7576번] 토마토 본문
문제 링크: 7576번 토마토
https://www.acmicpc.net/problem/7576
먼저 상자 전체를 순차적으로 탐색하면서 익은 토마토의 위치를 큐에 저장한다. 그 이후에 큐가 빌 때까지 BFS를 바로 수행해준다.
BFS를 끝마친 후 마지막에 익지 않은 토마토를 찾았을 때, for문을 일일이 탈출하지 말고 label을 이용하면 보다 편리하다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
static int[][] tomato;
static int[] drow = {0, 0, 1, -1}; // 동서남북
static int[] dcol = {1, -1, 0, 0}; // 동서남북
static int m;
static int n;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] mn = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
m = mn[0];
n = mn[1];
tomato = new int[n][m];
Queue<Integer[]> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
int[] temp = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
for (int j = 0; j < m; j++) {
int cur = temp[j];
tomato[i][j] = cur;
if (cur == 1)
queue.offer(new Integer[]{i, j});
}
}
while (!queue.isEmpty()) {
Integer[] cur = queue.poll();
int row = cur[0];
int col = cur[1];
for (int d = 0; d < 4; d++) {
int nrow = row + drow[d];
int ncol = col + dcol[d];
if (nrow<0 || ncol<0 || nrow>=n || ncol>=m || tomato[nrow][ncol] != 0) continue;
// visit
tomato[nrow][ncol] = tomato[row][col] + 1;
// offer to queue
queue.offer(new Integer[]{nrow, ncol});
}
}
int max = 0;
boolean flag = false;
outer:
for (int i=0; i<n; i++) {
for (int j =0; j<m; j++) {
if (tomato[i][j] == 0) {
flag = true;
break outer;
}
if (tomato[i][j] > max)
max = tomato[i][j];
}
}
if (flag) System.out.println(-1);
else System.out.println(max-1);
}
}
'콤퓨타 왕왕기초 > PS' 카테고리의 다른 글
[백준 4963번] 섬의 개수 (0) | 2020.12.30 |
---|---|
[백준 11724번] 연결 요소의 개수 (0) | 2020.12.30 |
[백준 2178번] 미로 탐색 (0) | 2020.12.30 |
[백준 1012번] 유기농 배추 (0) | 2020.12.29 |
[백준 2667번] 단지 번호 붙이기 (0) | 2020.12.28 |
Comments