티스토리 뷰
import java.io.*;
import java.util.*;
public class Main {
static int N, M;
static int[][] graph;
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};
// x,y 좌표가 함께 움직야하고, 날짜를 세야하는데 그걸 클래스 안에 넣었음
static class Dot {
int x;
int y;
int day;
public Dot(int x, int y, int day) {
this.x = x;
this.y = y;
this.day = day;
}
}
public static void main(String[] args) throws IOException {
input();
bfs();
}
// 입력
private static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
graph = new int[M][N];
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < N; j++) {
graph[i][j] = Integer.parseInt(st.nextToken());
}
}
}
private static void bfs() {
Queue<Dot> q = new LinkedList<Dot>();
int day = 0;
// 익은 토마토가 있는 좌표 찾아서 큐에 넣기
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (graph[i][j] == 1) {
q.offer(new Dot(i, j, 0));
}
}
}
// bfs
while (!q.isEmpty()) {
Dot dot = q.poll();
day = dot.day;
for (int i = 0; i < 4; i++) {
int nx = dot.x + dx[i];
int ny = dot.y + dy[i];
if (nx >= 0 && nx < M && ny >= 0 && ny < N) {
if (graph[nx][ny] == 0) {
graph[nx][ny] = 1;
q.offer(new Dot(nx, ny, day+1));
}
}
}
}
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 (graph[i][j] == 0) {
return false;
}
}
}
return true;
}
}
- 모르겠어서 다른 코드 봄
- 따라가기라도 해보자 ....
0. bfs사용을 생각
1. x,y 좌표를 같이 움직여야하니까 클래스를 따로 생성해서 사용함
1-1) day를 어짜피 카운팅 해야하니까 이 클래스안에 넣어서 사용함
2. graph를 돌면서 익은 토마토를 큐에 넣음
-> 익은토마토에서 상하좌우로 움직이니까
3. 큐에서 꺼내고, 상하좌우로 움직이며 범위안에 있고, 그게 안익은 토마토 0 이라면 익혀준다 1.
4. 익혀준 토마토를 다시 큐에 넣는데, 클래스의 day+1을 해준다.
5. while 문으로 큐가 빌때까지 반복하면 graph전체에 대해서 토마토 익히기가 완성된다.
6. 토마토가 없는 칸은 ? -> 이 칸때문에 익히는게 안된다면 graph안에 어딘가 0인 토마토가 존재할 것이다.
-> -1 출력, 아니면 지금까지 구한 큐에서 마지막으로 꺼낸 day를 출력
반응형
'PS > boj' 카테고리의 다른 글
boj)10828 - 스택구현 (0) | 2020.09.13 |
---|---|
boj)2644 - 촌수계산 (0) | 2020.09.05 |
boj)2178 - 미로 탐색 (0) | 2020.09.03 |
boj)1012 - 유기농 배추 (0) | 2020.09.03 |
boj)2667 - 단지번호붙이기 (0) | 2020.09.03 |
링크
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- js array
- 백준
- dreamcoding
- 김영한 http
- 이펙티브자바
- java
- GCP
- 이펙티브자바 아이템60
- 패스트캠퍼스 컴퓨터공학 완주반
- 김영한 JPA
- HTTP 완벽 가이드
- 프로그래머스 SQL
- http
- 이펙티브자바 스터디
- 드림코딩
- 모던자바스크립트
- 프로그래머스
- JS 딥다이브
- 가상 면접 사례로 배우는 대규모 시스템 설계 기초
- REST API
- 백기선 스터디
- js api
- 이펙티브자바 아이템59
- js promise
- 집 구하기
- BOJ
- JPA 연관관계 매핑
- 킹수빈닷컴
- Spring Security
- HTTP 완벽가이드
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함