https://www.acmicpc.net/problem/7576
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다. 하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마
www.acmicpc.net
Pair 클래스는 좌표를 저장하기 위한 클래스. check 함수는 2차원 배열 map 을 돌면서 0이 있으면(익지 않은 토마토가 있으면) -1 출력하기 위한 함수
제네릭: 클래스 내부에서 사용할 데이터 타입을 외부에서 지정하는 기법
|
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Main {
static int M, N, DAY = 0;
static int[][] map, dir = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };
static boolean[][] visited;
static Queue<Pair> queue = new LinkedList();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
M = sc.nextInt();
N = sc.nextInt();
map = new int[N][M];
visited = new boolean[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
map[i][j] = sc.nextInt();
if (map[i][j] == 1) {
queue.add(new Pair(i, j));
}
}
}
BFS();
if (!check()) {
System.out.println("-1");
return;
} else
System.out.println(DAY - 1);
}// end of main
public static void BFS() {
while (!queue.isEmpty()) {
int len = queue.size();
DAY++;
for (int j = 0; j < len; j++) {
Pair p = queue.poll();
visited[p.x][p.y] = true;
for (int i = 0; i < 4; i++) {
int nx = p.x + dir[i][0];
int ny = p.y + dir[i][1];
if (isInside(nx, ny) && !visited[nx][ny] == true && map[nx][ny] == 0) {
map[nx][ny] = 1;
queue.offer(new Pair(nx,ny));
}
}
}
}
}
public static boolean isInside(int x, int y) {
return x >= 0 && x < N && y >= 0 && y < M;
}
public static boolean check() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[i][j] == 0)
return false;
}
}
return true;
}
}// end of class
class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
//2차원 배열 - isInside
//4방
//최소 일수- BFS ,Queue
'ALGORITHM > 프로그래머스 | 백준 | 삼성 | 카카오' 카테고리의 다른 글
[백준] 2178번 미로탐색 (0) | 2020.04.01 |
---|---|
[백준] 2630번 색종이 만들기 (0) | 2020.04.01 |
[백준] 2468번 안전영역 (0) | 2020.04.01 |
[백준] 1012번 유기농 배추 (0) | 2020.04.01 |
[백준] 1260번 DFS와 BFS (0) | 2020.03.31 |