Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 세그먼트트리
- 문자열다루기
- component
- 스택
- dfs
- 완전탐색
- Android
- activity
- 생명주기
- 다이나믹프로그래밍
- BOJ
- 알고리즘
- BFS
- 코딩
- 코딩테스트
- 분할정복
- 운영체제
- 트리
- 프로그래머스
- 동적계획법
- 백준
- 그래프
- GIT
- 이분탐색
- 안드로이드
- 코틀린
- 카카오블라인드
- 문자열
- 배열
- 자바
Archives
- Today
- Total
HS_development_log
백준 7576번 - 토마토 / Java 본문
반응형
문제
https://www.acmicpc.net/problem/7576
BFS탐색 문제이다. 문제에 "최소 날짜"를 출력하라고 하는데 "최소"를 구하기 위해서는 BFS로 탐색해야 한다 DFS로는 구할 수 없다
토마토가 익으면 주변의 토마토를 모두 익게하므로 점점 익는 범위가 많아진다. 이 부분을 유의해서 동시적으로 구현해줘야 한다
알고리즘
-
입력받을 때 익어있는 토마토를 미리 큐에 넣어놓는다
-
q에 들어있는 개수만큼만 탐색을 하고 날짜를 세준다. 구분 없이 탐색을 하면 날짜를 셀 수 없기 때문
-
큐가 빌 때까지 2를 반복하고 답을 출력한다
소스코드
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
|
/*
* BOJ7576
* 2020.01.23
* Hyeonseong
*/
import java.util.*;
public class BOJ7576
{
public static void main(String[] args)
{
Solution s = new Solution();
}
}
class Node{
int x;
int y;
Node(int x, int y){
this.x = x;
this.y = y;
}
}
class Solution{
int m; // 가로
int n; // 세로
int answer;
int map[][];
boolean visit[][];
Queue<Node> ripe;
public Solution() {
Scanner scan = new Scanner(System.in);
m = scan.nextInt();
n = scan.nextInt();
answer = 0;
map = new int[n][m];
visit = new boolean[n][m];
ripe = new LinkedList<Node>();
for(int i=0;i<n;i++) {
map[i] = new int[m];
visit[i] = new boolean[m];
for(int j=0;j<m;j++) {
map[i][j] = scan.nextInt();
if(map[i][j]==1) {
ripe.add(new Node(i,j));
}
}
}
while(!ripe.isEmpty()) { // 토마토가 다 익을때 까지
bfs(ripe.size());
answer++;
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(map[i][j]==0) { // 안익은게 있으면 -1
System.out.println("-1");
System.exit(0);
}
}
}
System.out.println(answer-1);
}
public void bfs(int num) { //익은 토마토의 수만큼 돌린다
int dx[] = {-1,0,1,0};
int dy[] = {0,1,0,-1};
while(num-->0) {
Node t = ripe.poll();
for(int i=0;i<4;i++) {
int di = t.x+dx[i];
int dj = t.y+dy[i];
if(di>=0 && dj>=0 && di<n && dj<m) {
if(!visit[di][dj] && map[di][dj]==0) {
ripe.offer(new Node(di,dj)); // 익은 토마토 추가
visit[di][dj] = true;
map[di][dj] = 1;
}
}
}
}
}
}
|
cs |
반응형
'Algorithm-백준 > BFS,DFS' 카테고리의 다른 글
백준 6603 - 로또 / Java (0) | 2020.07.28 |
---|---|
백준 7562번 - 나이트의 이동 / Java (0) | 2020.02.05 |
백준 13023번 - ABCDE / Java (0) | 2020.02.05 |
백준 1939번 - 중량제한 / Java (0) | 2020.02.05 |
백준 1963번 - 소수 경로 / Java (0) | 2020.01.30 |