[Algorithm/Java] 백준 7569번 - 토마토
https://www.acmicpc.net/problem/7569
🔍 문제 풀이
문제 도식화
arr 원본은 유지하고 v 배열로 방문 체크를 했는데, 벽도 0이라서 모든 토마토가 익은 상태(0일 걸림) 와 벽(0 표시) 이 중복되는 문제가 생긴다.
그래서 최종 검사에서 if(arr[z][i][j] == -1) continue;
로 벽은 아예 스킵해줘야 “처음부터 다 익었으면 0 출력”이 제대로 동작한다.
💻 코드
전체 코드
import java.io.*;
import java.util.*;
public class Main {
static int[][][] arr;
static int[][][] v;
static int[] dz = {-1, 1, 0, 0, 0, 0};
static int[] dx = {0, 0, -1, 1, 0, 0};
static int[] dy = {0, 0, 0, 0, -1, 1};
static int col, row, h;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
col = Integer.parseInt(st.nextToken());
row = Integer.parseInt(st.nextToken());
h = Integer.parseInt(st.nextToken());
arr = new int[h][row][col];
v = new int[h][row][col];
Deque<int[]> dq = new ArrayDeque<>();
for(int z=0; z<h; z++){
for(int i=0; i<row; i++){
st = new StringTokenizer(br.readLine());
for(int j=0; j<col; j++){
arr[z][i][j] = Integer.parseInt(st.nextToken());
if(arr[z][i][j] == 1){
dq.offer(new int[]{z, i, j});
v[z][i][j] = 1;
}
}
}
}
bfs(dq);
int ans = 0;
for(int z=0; z<h; z++){
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
if(arr[z][i][j] == -1) continue; // 주의! 벽이면 건너뛰기
if(v[z][i][j] == 0){
System.out.println(-1);
return;
}
ans = Math.max(ans, v[z][i][j] - 1);
}
}
}
System.out.println(ans);
}
static void bfs(Deque<int[]> dq){
// 1. 바로 탐색
while(!dq.isEmpty()){
int[] cur = dq.poll();
int cz = cur[0], cx = cur[1], cy = cur[2];
// 2. 6방향, nz, nx, ny 범위
for(int d=0; d<6; d++){
int nz = cz + dz[d];
int nx = cx + dx[d];
int ny = cy + dy[d];
if(nz < 0 || nz >= h || nx < 0 || nx >= row || ny < 0 || ny >= col) continue;
// 3. 미방문 && 이동칸
if(arr[nz][nx][ny] == 0 && v[nz][nx][ny] == 0){
v[nz][nx][ny] = v[cz][cx][cy] + 1;
dq.offer(new int[]{nz, nx, ny});
}
}
}
}
}
스켈레톤 코드
import java.io.*;
import java.util.*;
public class Main {
static int[][][] arr;
static int[] dz = {-1, 1, 0, 0, 0, 0};
static int[] dx = {0, 0, -1, 1, 0, 0};
static int[] dy = {0, 0, 0, 0, -1, 1};
static int col, row, h;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
col = Integer.parseInt(st.nextToken());
row = Integer.parseInt(st.nextToken());
h = Integer.parseInt(st.nextToken());
arr = new int[h][row][col];
Deque<int[]> dq = new ArrayDeque<>();
}
static void bfs(Deque<int[]> dq){
}
}
댓글남기기