728x90
반응형
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Tomato {
int x;
int y;
public Tomato(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Main {
public static int m;
public static int n;
public static int[][] arr;
public static int[] dirX = { -1, 1, 0, 0 };
public static int[] dirY = { 0, 0, -1, 1 };
public static Queue<Tomato> queue;
public static int bfs() {
while (!queue.isEmpty()) {
Tomato tomato = queue.poll();
int x = tomato.x;
int y = tomato.y;
for (int i = 0; i < 4; i++) {
int X = tomato.x + dirX[i];
int Y = tomato.y + dirY[i];
if (X >= 0 && X < n && Y >= 0 && Y < m) {
if (arr[X][Y] == 0) {
queue.add(new Tomato(X, Y));
arr[X][Y] = arr[x][y] + 1;
}
}
}
}
int result = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (arr[i][j] == 0) {
return -1;
}
result = Math.max(result, arr[i][j]);
}
}
if (result == 1) {
return 0;
} else {
return (result - 1);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
m = sc.nextInt();
n = sc.nextInt();
arr = new int[n][m];
queue = new LinkedList<Tomato>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = sc.nextInt();
if (arr[i][j] == 1) {
queue.add(new Tomato(i, j));
}
}
}
System.out.println(bfs());
}
}
|
cs |
7569번과 동일한 문제
https://we1cometomeanings.tistory.com/166
[java 백준]실버 1/ 7569번 토마토
https://www.acmicpc.net/problem/7569 7569번: 토마토 첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수
we1cometomeanings.tistory.com
728x90
반응형
'알고리즘 > 그래프' 카테고리의 다른 글
[java 백준] 골드 3/ 2146번 다리 만들기 (0) | 2021.10.13 |
---|---|
[java 백준]실버 1/2178번 미로찾기 (0) | 2021.10.09 |
[java 백준]실버 1/ 7569번 토마토 (0) | 2021.10.03 |
[java 백준]실버 2/ 4963번 섬의 개수 (0) | 2021.09.30 |
[java 백준] 실버 1/2667번 단지번호 붙이기 (0) | 2021.09.29 |
댓글