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
- java 내림
- 백준 4375
- 백준 11723
- 백준 16927
- 백준 17425
- 프로그래머스 숫자의 표현 java
- 프로그래머스 옹알이 java
- sort
- java 반올림
- Math.ceil()
- 백준 16935
- Codility
- 백준 15661
- 프로그래머스 네트워크 java
- 코딩테스트
- 알고리즘
- 프로그래머스 도둑질 java
- java
- mysql
- 네트워크
- 백준 18290
- 0으로 채우기
- time complexity
- 백준 14391
- 프로그래머스 연속된 수의 합 java
- Math.floor()
- java 올림
- Algorithm
- 자바
- Arrays
Archives
- Today
- Total
취미처럼
[백준] 7576번 토마토 본문
https://www.acmicpc.net/problem/7576
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토
www.acmicpc.net
익지 않은 토마토의 카운트를 세서
익었다는 처리를 할 때 빼줌
방문여부를 누적해서 최종 날짜를 셈
import java.util.*;
import java.io.*;
class Node {
int y;
int x;
Node(int y, int x) {
this.y = y;
this.x = x;
}
}
public class Main {
// 가로
static int M;
// 세로
static int N;
static int[][] map;
static int[][] visit;
static int[] dy = { 0, 1, 0, -1 };
static int[] dx = { 1, 0, -1, 0 };
// 안익은 토마토
static int count = 0;
// 날짜
static int day = 0;
static Queue<Node> q = new LinkedList<>();
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
M = Integer.parseInt(st.nextToken());
N = Integer.parseInt(st.nextToken());
map = new int[N][M];
visit = new int[N][M];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < M; j++) {
// 방문여부 초기화
visit[i][j] = -1;
int tomato = Integer.parseInt(st.nextToken());
map[i][j] = tomato;
if (tomato == 1) {
q.offer(new Node(i, j)); // 토마토가 익었을 때 큐에 넣어줌
visit[i][j] = 0;
} else if (tomato == 0) { // 안 익은 토마토 카운트 올려줌
count++;
}
}
}
// 안 익은 토마토 없으면 종료
if (count == 0) {
System.out.print(0);
System.exit(0);
}
bfs();
// 아직 안 익은 토마토가 남아 있으면
if (count > 0) {
System.out.println(-1);
} else {
System.out.println(day);
}
}
public static void bfs() {
// 1 이미 익은거
// 0 안익은거
// -1 없는거
while (!q.isEmpty()) {
Node node = q.poll();
for (int i = 0; i < 4; i++) {
int ny = dy[i] + node.y;
int nx = dx[i] + node.x;
// 범위 벗어날 때
if (ny < 0 || ny >= N || nx < 0 || nx >= M) {
continue;
}
// 토마토 없거나 이미 방문했을 경우
if (map[ny][nx] == -1 || visit[ny][nx] != -1) {
continue;
}
// 익은 토마토 큐에넣어주고
q.offer(new Node(ny, nx));
// 안 익은 거에서 빼줌
count--;
// 방문여부를 현재노드 + 1
visit[ny][nx] = visit[node.y][node.x] + 1;
// 해당 날짜가 최종인지 구분
if (day < visit[ny][nx]) {
day = visit[ny][nx];
}
}
}
}
}
'Algorithm > 백준' 카테고리의 다른 글
[백준] 1697번 숨바꼭질 (0) | 2021.03.11 |
---|---|
[백준] 7562번 나이트의 이동 (0) | 2021.03.11 |
[백준] 2178번 미로 탐색 (0) | 2021.03.11 |
[백준] 2667번 단지번호붙이기 (0) | 2021.03.11 |
[백준] 1707번 이분 그래프 (0) | 2021.03.11 |
Comments