Repository navigation
Expand file tree
/
Copy pathProblem8_12.java
More file actions
96 lines (81 loc) · 1.83 KB
/
Copy pathProblem8_12.java
File metadata and controls
96 lines (81 loc) · 1.83 KB
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
86
87
88
89
90
91
92
93
94
95
96
package inflearn;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/*
* 토마토(BFS 활용)
* */
public class Problem8_12 {
static int[][] box;
static int[][] dis;
static int[] dx = {0, 1, 0, -1};
static int[] dy = {1, 0, -1, 0};
static int n;
static int m;
static class Pointer {
int x;
int y;
public Pointer(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void BFS() {
Queue<Pointer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (box[i][j] == 1) {
queue.offer(new Pointer(i, j));
}
}
}
while(!queue.isEmpty()) {
Pointer current = queue.poll();
for (int i = 0; i < 4; i++) {
int nx = current.x + dx[i];
int ny = current.y + dy[i];
if (nx >= 0 && nx < n && ny >=0 && ny < m && box[nx][ny] == 0) {
box[nx][ny] = 1;
queue.offer(new Pointer(nx, ny));
dis[nx][ny] = dis[current.x][current.y] + 1;
}
}
}
}
public static void printResult() {
boolean flag = true;
int answer = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (box[i][j] == 0) {
flag = false; // 모두 익지 않은 경우
break;
}
}
}
if (flag) { // 처음부터 다 익은경우 혹은 최소 날짜 출력
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
answer = Math.max(answer, dis[i][j]);
}
}
System.out.println(answer);
} else {
System.out.println("-1");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
m = sc.nextInt(); // 가로 칸
n = sc.nextInt(); // 세로 칸
box = new int[n][m];
dis = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
box[i][j] = sc.nextInt();
}
}
Problem8_12.BFS();
Problem8_12.printResult();
}
}