| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | |||||
| 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 10 | 11 | 12 | 13 | 14 | 15 | 16 |
| 17 | 18 | 19 | 20 | 21 | 22 | 23 |
| 24 | 25 | 26 | 27 | 28 | 29 | 30 |
| 31 |
Tags
- 토마토
- 자바
- 프로그래머스
- 정렬
- dfs
- 이코테
- 깃허브 프로필
- 알고리즘
- 다익스트라
- Java
- GIT
- 분할정복
- 깃허브
- Python
- DP
- 그래프
- 그래프탐색
- BFS
- 15686
- 알고리즘고득점Kit
- 월간 코드 챌린지 시즌1
- 조합
- 구현
- Summer/Winter Coding(~2018)
- 정수 삼각형
- 프로그래멋
- 1932
- 백준
- Lv2
- 완전탐색
Archives
- Today
- Total
갱스터하우스
[Java] 백준 7569.토마토 본문
➡️문제 링크
https://www.acmicpc.net/problem/7569
💡아이디어
bfs 돌리기
저번에 풀었던 7576 토마토 문제랑 같은 문제지만, 이번에는 3차원 상에서 토마토를 익혀야 한다
[Java] 백준 7576.토마토
➡️문제 링크https://www.acmicpc.net/problem/7576 💡아이디어보자마자 bfs 문제라고 판단했다 보관 후 하루가 지나면, 익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을
imrud.tistory.com
✏️문제 풀이
1. bfs - 성공
import java.io.*;
import java.util.*;
public class Main {
static int N, M, H;
static int [][][] map;
static Queue<int[]> que = new LinkedList<>();
static int count = 0;
static int [] dh = {0, 0, 0, 0, -1, 1};
static int [] dx = {-1, 0, 1, 0, 0, 0};
static int [] dy = {0, 1, 0, -1, 0, 0};
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
M = Integer.parseInt(st.nextToken());
N = Integer.parseInt(st.nextToken());
H = Integer.parseInt(st.nextToken());
map = new int[H][N][M];
for(int h = 0; h < H; h++) {
for(int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for(int j = 0; j < M; j++) {
map[h][i][j] = Integer.parseInt(st.nextToken());
if(map[h][i][j] == 1) que.add(new int [] {h, i, j, 0}); // 익은 토마토 위치
if(map[h][i][j] == 0) count++; // 익지 않은 토마토 개수 증가
}
}
}
// 탐색 및 출력
System.out.println(bfs());
}
static int bfs() {
int result = 0;
while(!que.isEmpty()) {
int [] curPoint = que.poll();
if(count == 0) break;
for(int i = 0; i < 6; i++) {
int th = dh[i] + curPoint[0];
int tx = dx[i] + curPoint[1];
int ty = dy[i] + curPoint[2];
if(checkRange(th, tx, ty) && map[th][tx][ty] == 0) {
map[th][tx][ty] = 1; // 익은 처리
count--; // 익었으니 개수 차감
que.add(new int [] {th, tx, ty, curPoint[3]+1});
}
}
result = curPoint[3]+1;
}
if(count == 0) return result;
else return -1; // 익지 않은 토마토 존재
}
static boolean checkRange(int h, int x, int y) {
return h >= 0 && h < H && x >= 0 && x < N && y >= 0 && y < M;
}
}
'코테 문제 > 백준' 카테고리의 다른 글
| [Java] 백준 16928.뱀과사다리게임 (0) | 2026.02.14 |
|---|---|
| [Java] 백준 10026.적록색약 (0) | 2026.02.12 |
| [Java] 백준 1931.회의실 배정 (0) | 2026.02.07 |
| [Java] 백준 7576.토마토 (1) | 2026.02.06 |
| [Java] 백준 1074.Z (0) | 2026.02.05 |