-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path토마토.java
95 lines (77 loc) · 2.4 KB
/
토마토.java
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
import java.util.*;
import java.io.*;
public class Main {
public static int M;
public static int N;
public static int res;
public static int[][] map = new int[1001][1001];
public static boolean[][] visit = new boolean[1001][1001];
public static int[] dx = {0,0,1,-1};
public static int[] dy = {1,-1,0,0};
public static Queue<Node> queue = new LinkedList<>();
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());
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());
}
}
for(int i =0; i < N; i++){
for(int j = 0; j < M; j++){
if(map[i][j] == 1){
queue.add(new Node(i,j,0));
}
}
}
bfs();
}
static void bfs(){
int day = 0;
while (!queue.isEmpty()){
Node cur = queue.poll();
day = cur.d;
for(int i = 0; i < 4; i++){
int newx = cur.x + dx[i];
int newy = cur.y + dy[i];
if(check(newx, newy)){
map[newx][newy] = 1;
visit[newx][newy] = true;
queue.add(new Node(newx,newy, cur.d+1));
}
}
}
if(checkTomato()){
System.out.print(day);
}
else{
System.out.print(-1);
}
}
static boolean checkTomato() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if(map[i][j] == 0){
return false;
}
}
}
return true;
}
static boolean check(int x, int y){
return x >= 0 && x < N && y >= 0 && y < M && !visit[x][y] && map[x][y] == 0;
}
static class Node{
int x;
int y;
int d;
public Node(int x, int y, int d) {
this.x = x;
this.y = y;
this.d = d;
}
}
}