-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tomato.java
89 lines (79 loc) · 2.2 KB
/
Tomato.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
package bfs;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class Coordinates{
short row;
short col;
public Coordinates(short row, short col){
this.row = row;
this.col = col;
}
}
public class Tomato {
public static int zeros = 0;
public static void checkNeighbor(byte field[][], short row, short col, Queue<Coordinates> queue){
if(field[row][col] == 0){
queue.add(new Coordinates((short)(row), (short)(col)));
field[row][col] = 1;
zeros--;
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
short M = Short.parseShort(st.nextToken()); //col
short N = Short.parseShort(st.nextToken()); //row
byte field[][] = new byte[N][M];
Queue<Coordinates> queue = new LinkedList<Coordinates>();
int days = 0;
/*
* inputs
* */
for (short i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (short j = 0; j < M; j++){
field[i][j] = Byte.parseByte(st.nextToken());
switch(field[i][j]){
case 0:
zeros++;
break;
case 1:
queue.add(new Coordinates(i, j));
break;
}
}
}
queue.add(new Coordinates((short)-1, (short)-1)); //end flag
/*
* bfs
* */
while(!queue.isEmpty() && zeros >= 0){
Coordinates temp = queue.poll();
if(temp.row == -1){ //when find end of the queue.(one cycle)
if(queue.isEmpty())
break;
else{
days++;
queue.add(temp);
continue;
}
}
//boundary check
if(temp.row > 0)
checkNeighbor(field, (short)(temp.row - 1), (short)(temp.col), queue);
if(temp.col > 0)
checkNeighbor(field, (short)(temp.row), (short)(temp.col - 1), queue);
if(temp.row < N - 1)
checkNeighbor(field, (short)(temp.row + 1), (short)(temp.col), queue);
if(temp.col < M - 1)
checkNeighbor(field, (short)(temp.row), (short)(temp.col + 1), queue);
}
if(zeros == 0)
System.out.println(days);
else
System.out.println(-1);
}
}