BOJ 7576번 : 토마토 본문
BFS를 사용하는 문제였다. 이런저런 조건이 많이 붙어 코드들이 조금 길어졌다....
<Solution>
전반적으로 전문제에서도 사용했던 BFS와 비슷했다. 하지만, 익은 토마토의 위치(1)들이 여러개 있으므로, 시작부터 Queue에 좌표들을 넣어놓는 과정이 필수이다.
토마토가 익는 시점을 알기위해 max 값을 방문시마다 업데이트를 해주고, 모든 토마토가 익었는지를 판별하는 부분들이 추가되어 추가적인 코드들이 필요했다.
일단, 모든 토마토가 익었는지를 판단하기 위해서 방문을 하거나, -1(벽)입 부분을 모두 count 하여 m*n과 비교하였다.
<소스코드>
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
|
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
int arr[1002][1002] = { 0, };
int chk[1002][1002] = { 0, };
int _max_ = 0;
int cnt = 0;
queue<int>qx;
queue<int>qy;
void bfs() {
int temp_x = qx.front();
int temp_y = qy.front();
qx.pop();
qy.pop();
_max_ = (_max_ <= chk[temp_y][temp_x]) ? chk[temp_y][temp_x] : _max_;
if (!chk[temp_y + 1][temp_x] && !arr[temp_y + 1][temp_x]) { // 아래
chk[temp_y + 1][temp_x] = chk[temp_y][temp_x] + 1;
cnt++;
}
if (!chk[temp_y][temp_x + 1] && !arr[temp_y][temp_x + 1]) { // 오른
chk[temp_y][temp_x + 1] = chk[temp_y][temp_x] + 1;
cnt++;
}
if (!chk[temp_y - 1][temp_x] && !arr[temp_y - 1][temp_x]) { // 위
chk[temp_y - 1][temp_x] = chk[temp_y][temp_x] + 1;
cnt++;
}
if (!chk[temp_y][temp_x - 1] && !arr[temp_y][temp_x - 1]) { // 왼
chk[temp_y][temp_x - 1] = chk[temp_y][temp_x] + 1;
cnt++;
}
}
}
int main() {
memset(arr, -1, sizeof(arr));
memset(chk, 0, sizeof(chk));
int m, n;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
cin >> arr[i][j];
if (arr[i][j] == 1) {
cnt++;
}
else if (arr[i][j] == -1) {
chk[i][j] = 1;
cnt++;
}
}
}
if (qx.empty())
cout << -1 << endl;
else if (qx.size() == m * n)
cout << 0 << endl;
else {
bfs();
if (cnt == m * n)
cout << _max_ << endl;
else
cout << -1 << endl;
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
|
<문제>
https://www.acmicpc.net/problem/7576
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다. 하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마
www.acmicpc.net
'BOJ' 카테고리의 다른 글
BOJ 1697번 : 숨바꼭질 (0) | 2020.04.21 |
---|---|
BOJ 7569번 : 토마토 (3차원) (0) | 2020.04.19 |
BOJ 2178번 : 미로탐색 (0) | 2020.04.14 |
BOJ 2667번 : 단지번호붙이기 (0) | 2020.04.14 |
BOJ 2606번 : 바이러스 (0) | 2020.04.14 |
Comments