728x90
https://www.acmicpc.net/problem/7576
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토
www.acmicpc.net
// 코드
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
|
import java.util.*;
import java.io.*;
public class Main{
// 상, 하, 좌, 우
static int[][] dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
static int N, M;
static int[][] arr;
static int[][] result;
static int BFS() {
Deque<int[]> deq = new LinkedList<>();
for(int i=0; i<N; i++) {
for(int j=0; j<M; j++) {
if(arr[i][j] == 1) deq.add(new int[]{i, j});
}
}
while(!deq.isEmpty()) {
int[] getV = deq.pop();
for(int i=0; i<4; i++) {
// 상, 하, 좌, 우
int ny = dir[i][0] + getV[0];
int nx = dir[i][1] + getV[1];
if((0 <= ny && ny < N) && (0 <= nx && nx < M) && (arr[ny][nx] == 0)) {
arr[ny][nx] = arr[getV[0]][getV[1]] + 1;
deq.add(new int[]{ny, nx});
}
}
}
int result = Integer.MIN_VALUE;
for(int[] ar1 : arr) {
for(int ar2 : ar1) {
if(ar2 == 0) return -1;
result = Math.max(result, ar2);
}
}
if(result == 1) return 0;
else return result - 1;
}
// main
public static void main(String[] args) throws Exception {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
M = Integer.parseInt(st.nextToken());
N = Integer.parseInt(st.nextToken());
arr = new int[N][M];
result = new int[N][M];
for(int i=0; i<N; i++) {
arr[i] = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
}
int resVal = BFS();
bw.write(String.valueOf(resVal));
br.close();
bw.flush();
bw.close();
}
}
|
cs |
반응형
'CS > 알고리즘_문제풀이(자바)' 카테고리의 다른 글
쉬운 계단 수 (0) | 2021.10.07 |
---|---|
1, 2, 3 더하기 5 (0) | 2021.10.07 |
미로 탐색 (0) | 2021.10.06 |
N과 M (7) (0) | 2021.10.05 |
N과 M (8) (0) | 2021.10.05 |