-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtomato.java
More file actions
87 lines (70 loc) · 1.56 KB
/
tomato.java
File metadata and controls
87 lines (70 loc) · 1.56 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
package graph;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class tomato {
public static int n, m, day;
public static int box[][];
static int[] dx = {0,1,0,-1};
static int[] dy = {1,0,-1,0};
static class Toma{
int x;
int y;
int day;
public Toma(int x, int y, int day) {
this.x = x;
this.y = y;
this.day = day;
}
}
public static void bfs() {
Queue<Toma> q = new LinkedList<Toma>();
day = 0;
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
if(box[i][j]==1)
q.offer((new Toma(i,j,0)));
}
}
while(!q.isEmpty()) {
Toma toma = q.poll();
day = toma.day;
for(int i=0; i<4; i++) {
int nx = toma.x + dx[i];
int ny = toma.y + dy[i];
if(nx >= 0 && ny >=0 && nx < m && ny < n) {
if(box[nx][ny]==0) {
box[nx][ny]=1;
q.add(new Toma(nx,ny,day+1));
}
}
}
}
}
public static void main(String[] args) {
//#7576¹ø_Å丶Åä
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
box = new int[1000][1000];
for(int i =0; i<m; i++) {
for(int j=0; j<n; j++) {
box[i][j] = sc.nextInt();
}
}
bfs();
if(checkTomato())
System.out.println(day);
else
System.out.println(-1);
}
static boolean checkTomato() {
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
if(box[i][j] == 0)
return false;
}
}
return true;
}
}