백준 [3055] 탈출
문제보기
소스코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int R, C, ans;
static char[][] map;
static int[] dx = { -1, 1, 0, 0 };
static int[] dy = { 0, 0, -1, 1 };
static Queue<int[]> waterQueue;
static Queue<int[]> dochQueue;
static boolean[][] visited;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
R = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
ans = 987654321;
map = new char[R][C];
waterQueue = new LinkedList<>();
dochQueue = new LinkedList<>();
visited = new boolean[R][C];
for (int i = 0; i < R; i++) {
String str = br.readLine();
for (int j = 0; j < C; j++) {
map[i][j] = str.charAt(j);
if (map[i][j] == '*') { // 물
waterQueue.add(new int[] { i, j });
} else if (map[i][j] == 'S') { // 도치
dochQueue.add(new int[] { i, j, 0 });
visited[i][j] = true;
}
}
}
bfs(waterQueue.size(), dochQueue.size());
}
public static void bfs(int waterSize, int dochSize) {
boolean flag = false; // 도치 이동유무
for (int i = 0; i < dochSize; i++) {
int[] q = dochQueue.poll();
if (map[q[0]][q[1]] == '*')
continue;
for (int k = 0; k < 4; k++) {
int x = q[0] + dx[k];
int y = q[1] + dy[k];
if (isRange(x, y) && !visited[x][y] && (map[x][y] == '.' || map[x][y] == 'D')) {
if (map[x][y] == 'D') {
System.out.println(q[2] + 1);
System.exit(0);
}
dochQueue.add(new int[] { x, y, q[2] + 1 });
visited[x][y] = true;
flag = true;
}
}
}
if (!flag) {
System.out.println("KAKTUS");
System.exit(0);
}
for (int i = 0; i < waterSize; i++) { // 홍수
int[] q = waterQueue.poll();
for (int k = 0; k < 4; k++) {
int x = q[0] + dx[k];
int y = q[1] + dy[k];
if (isRange(x, y) && map[x][y] == '.') {
waterQueue.add(new int[] { x, y });
map[x][y] = '*';
}
}
}
bfs(waterQueue.size(), dochQueue.size());
}
public static boolean isRange(int x, int y) {
return x >= 0 && y >= 0 && x < R && y < C;
}
}