최's 먹공로그
BOJ7576_토마토 본문
https://www.acmicpc.net/problem/7576
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 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static Queue<Integer> q = new LinkedList<>();
static int[] dx = {0,1,0,-1};
static int[] dy = {-1,0,1,0};
static int cnt;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine().trim(), " ");
int C = Integer.parseInt(st.nextToken());
int R = Integer.parseInt(st.nextToken());
int[][] map = new int[R][C];
int zero_cnt = 0;
for (int i = 0; i < R; i++) {
StringTokenizer st2 = new StringTokenizer(br.readLine().trim(), " ");
for (int j = 0; j < C; j++) {
int number = Integer.parseInt(st2.nextToken());
// 입력할때 안익은 토마토를 카운트
if(number == 0) {
zero_cnt++;
}
map[i][j] = number;
}
}
// 안익은 토마토가 없으면 0출력하고 끝
if(zero_cnt == 0) {
System.out.println(0);
return;
}
// q에 익은 토마토의 위치를 저장
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
if(map[i][j] == 1) {
q.add(i);
q.add(j);
}
}
}
cnt = -1;
bfs(map, C, R);
// bfs 다돌고 와서도 map에 0이 남아있으면 -1출력하고 끝
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
if(map[i][j] == 0) {
System.out.println(-1);
return;
}
}
}
System.out.println(cnt);
} // end of main
private static void bfs(int[][] map, int y, int x) {
while(!q.isEmpty()) {
cnt++;
int q_size = q.size()/2; // q의 크기는 계속 변해서 한번 저장해주고 써야됨
for (int i = 0; i < q_size; i++) { // 큐에 (0,0)이게 한개니깐 /2
int tomato_x = q.poll(); // 한턴에 뺀 토마토 x,y 좌표
int tomato_y = q.poll();
for (int j = 0; j < 4; j++) { // 인접 검사
int nx = tomato_x + dx[j];
int ny = tomato_y + dy[j];
if(nx>=0 && nx<x && ny>=0 && ny<y &&
map[nx][ny] == 0) {
map[nx][ny] = 1;
q.add(nx);
q.add(ny);
}
}
}
//cnt++;
} // end of q while
} // end of bfs
} // end of class
|
cs |
'APS' 카테고리의 다른 글
BOJ14502_연구소 (3) | 2019.03.14 |
---|---|
BOJ7569_토마토 (0) | 2019.03.12 |
SEA7236_저수지의 물의 총 깊이 구하기 (0) | 2019.03.10 |
SEA1861_정사각형 방 (0) | 2019.03.10 |
SEA7234_안전 기지(User Problem) (2) | 2019.03.07 |