성능 요약
메모리: 151576 KB, 시간: 632 ms
분류
너비 우선 탐색(bfs), 그래프 이론(graphs), 그래프 탐색(graph_traversal)
문제 설명
철수의 토마토 농장에서는 토마토를 보관하는 큰 창고를 가지고 있다. 토마토는 아래의 그림과 같이 격자 모양 상자의 칸에 하나씩 넣어서 창고에 보관한다.
창고에 보관되는 토마토들 중에는 잘 익은 것도 있지만, 아직 익지 않은 토마토들도 있을 수 있다. 보관 후 하루가 지나면, 익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을 받아 익게 된다. 하나의 토마토의 인접한 곳은 왼쪽, 오른쪽, 앞, 뒤 네 방향에 있는 토마토를 의미한다. 대각선 방향에 있는 토마토들에게는 영향을 주지 못하며, 토마토가 혼자 저절로 익는 경우는 없다고 가정한다. 철수는 창고에 보관된 토마토들이 며칠이 지나면 다 익게 되는지, 그 최소 일수를 알고 싶어 한다.
토마토를 창고에 보관하는 격자모양의 상자들의 크기와 익은 토마토들과 익지 않은 토마토들의 정보가 주어졌을 때, 며칠이 지나면 토마토들이 모두 익는지, 그 최소 일수를 구하는 프로그램을 작성하라. 단, 상자의 일부 칸에는 토마토가 들어있지 않을 수도 있다.
입력
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다. 하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마토가 들어있지 않은 칸을 나타낸다.
토마토가 하나 이상 있는 경우만 입력으로 주어진다.
출력
여러분은 토마토가 모두 익을 때까지의 최소 날짜를 출력해야 한다. 만약, 저장될 때부터 모든 토마토가 익어있는 상태이면 0을 출력해야 하고, 토마토가 모두 익지는 못하는 상황이면 -1을 출력해야 한다.
bfs로 구현해야 한다는 건 바로 생각해냈다. 인접한 노드들을 방문할 때 day는 1씩 증가하기 때문이다.
그러나 기존의 bfs를 활용하면 하루에 2개 이상의 토마토가 익어 있을 경우 day를 세기가 어렵다.
그래서 인접한 토마토들을 익은 토마토의 값에 1씩 더해주며 bfs를 진행하였다. 이 과정을 반복하면 토마토의 값 중 가장 큰 값이 모든 토마토가 익기까지 걸린 시간이 될 것이다.
static void bfs() {
Queue<Integer> q_r = new LinkedList<>(); // r을 담을 queue
Queue<Integer> q_c = new LinkedList<>(); // c를 담을 queue
int cnt = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++) {
if (map[i][j] == 1) {
q_r.add(i);
q_c.add(j);
}
}
while (!q_r.isEmpty()) {
int r = q_r.poll();
int c = q_c.poll();
visited[r][c] = true;
int data = map[r][c];
for (int d = 0; d < 4; d++) {
int nr = r + dr[d];
int nc = c + dc[d];
if (nr >= 0 && nr < N && nc >= 0 && nc < M && map[nr][nc] == 0 && !visited[nr][nc]) {
map[nr][nc] = data + 1; // day를 세기 편하게 하려고 이전 data(연결 노드)+1을 해줬음
if (data > cnt)
cnt = data; // cnt를 update
q_r.add(nr);
q_c.add(nc);
}
}
}
또 day의 초기값을 -1로 하고, bfs가 끝나면 0이 있는지를 체크하여 0이 없을 때에만 day를 cnt로 업데이트하였다.
boolean checkZero = false;
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++) {
if (map[i][j] == 0)
checkZero = true;
}
if (!checkZero) { // 0이 없으면 day를 update, 0이 있다면 그대로 -1 출력
day = cnt;
return;
}
전체 코드
package Gold.g5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class BOJ_7576_토마토 {
static int[][] map;
static boolean[][] visited;
static int N, M; // N은 row M은 col
static int day = -1; // -1로 초기화, 모두 채울 수 없으면 -1 출력하도록
static int[] dr = { -1, 1, 0, 0 };
static int[] dc = { 0, 0, -1, 1 };
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];
visited = new boolean[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());
} // 입력
bfs();
System.out.println(day);
}
static void bfs() {
Queue<Integer> q_r = new LinkedList<>(); // r을 담을 queue
Queue<Integer> q_c = new LinkedList<>(); // c를 담을 queue
int cnt = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++) {
if (map[i][j] == 1) {
q_r.add(i);
q_c.add(j);
}
}
while (!q_r.isEmpty()) {
int r = q_r.poll();
int c = q_c.poll();
visited[r][c] = true;
int data = map[r][c];
for (int d = 0; d < 4; d++) {
int nr = r + dr[d];
int nc = c + dc[d];
if (nr >= 0 && nr < N && nc >= 0 && nc < M && map[nr][nc] == 0 && !visited[nr][nc]) {
map[nr][nc] = data + 1; // day를 세기 편하게 하려고 이전 data(연결 노드)+1을 해줬음
if (data > cnt)
cnt = data; // cnt를 update
q_r.add(nr);
q_c.add(nc);
}
}
}
boolean checkZero = false;
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++) {
if (map[i][j] == 0)
checkZero = true;
}
if (!checkZero) { // 0이 없으면 day를 update, 0이 있다면 그대로 -1 출력
day = cnt;
return;
}
}
}
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 2448 별 찍기 - 11 (자바/Java) 재귀, 분할정복 (0) | 2022.09.19 |
---|---|
[벡준] 5014 - 스타트링크 (자바/Java) (0) | 2022.09.15 |
[백준] 2667 - 단지 번호 붙이기 (자바/Java) (0) | 2022.09.13 |
[백준] 2263 - 트리의 순회 (자바/Java) (0) | 2022.09.12 |
[백준] 4803 - 트리 (자바/Java) (0) | 2022.09.12 |