반응형
문제 |
소스 |
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int n,m,x,y,_x,_y,result;
static int map[][];
static boolean visit[][];
static int dx[] = {0, 1, 0, -1}; // 우, 하, 좌, 상
static int dy[] = {1, 0, -1, 0};
static Queue<Integer> qx = new LinkedList<Integer>();
static Queue<Integer> qy = new LinkedList<Integer>();
public static void bfs() {
result = 0;
while (!qx.isEmpty() && !qy.isEmpty()){
x = qx.poll();
y = qy.poll();
visit[x][y] = true;
for (int i=0; i<4; i++) {
_x = x + dx[i];
_y = y + dy[i];
if (_x >= 0 && _y >= 0 && _x < m && _y < n) {
if (map[_x][_y] == 0 && visit[_x][_y] == false){
qx.add(_x);
qy.add(_y);
visit[_x][_y] = true;
map[_x][_y] = map[x][y] + 1;
result = map[_x][_y];
}
}
}
}
// 익지 않은 토마토가 있는지 체크
for (int i=0; i<m; i++){
for (int j=0; j<n; j++){
if (map[i][j] == 0){
result = -1;
}
}
}
if (result > 0){
System.out.println(result-1);
} else {
System.out.println(result);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
map = new int[m][n];
visit = new boolean[m][n];
int temp;
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
temp = sc.nextInt();
map[i][j] = temp;
if (temp == 1) { // 익은 토마토
qx.add(i);
qy.add(j);
}
}
}
bfs();
}
}출처 |
반응형
'알고리즘 > JAVA' 카테고리의 다른 글
| [JAVA] 백준 알고리즘 1978 : 소수 찾기 (0) | 2018.08.28 |
|---|---|
| [JAVA] 백준 알고리즘 2609 : 최대공약수와 최소공배수 (0) | 2018.08.28 |
| [JAVA] 백준 알고리즘 2178 : 미로 탐색 (BFS) (1) | 2018.08.28 |
| [JAVA] 백준 알고리즘 1260 : DFS와 BFS (0) | 2018.08.24 |
| [JAVA] 백준 알고리즘 1003 : 피보나치 함수 (0) | 2018.08.02 |