public class Main {
static int[] ax = new int[]{0, 0, 1, -1};
static int[] ay = new int[]{1, -1, 0, 0};
static int R,C;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split(" ");
R = Integer.parseInt(s[0]);
C = Integer.parseInt(s[1]);
int[][] map = new int[R][C];
boolean[][] visited = new boolean[R][C];
Queue<Node> hedgehog = new LinkedList<>();
Queue<Node> water = new LinkedList<>();
for (int i = 0; i < R; i++) {
String[] strings = br.readLine().split("");
for (int j = 0; j < C; j++) {
String str = strings[j];
int cur = 0;
if (str.equals("*")) {
cur = -1;
water.offer(new Node(j, i));
} else if (str.equals("D")) {
cur = 2;
} else if (str.equals("X")) {
cur = -2;
} else if (str.equals("S")) {
cur = 1;
hedgehog.offer(new Node(j, i, 0));
visited[i][j] =true;
}
map[i][j] = cur;
}
}
while (!hedgehog.isEmpty()) {
//물 이동
int n1 = water.size();
for (int j=0;j<n1;j++) {
Node waterPoll = water.poll();
for (int i = 0; i < 4; i++) {
int nx = waterPoll.x + ax[i];
int ny = waterPoll.y + ay[i];
if (!checkRange(nx, ny))
continue;
if (map[ny][nx] != -2 && map[ny][nx] != 2 && map[ny][nx] != -1) {
map[ny][nx] = -1;
water.offer(new Node(nx, ny));
}
}
}
//고슴도치 이동
int n2 = hedgehog.size();
for (int j=0;j<n2;j++) {
Node poll = hedgehog.poll();
for (int i = 0; i < 4; i++) {
int nx = poll.x + ax[i];
int ny = poll.y + ay[i];
if (!checkRange(nx, ny))
continue;
if (map[ny][nx]==2) {
System.out.println(poll.count+1);
return;
}
if (map[ny][nx] != -1 && map[ny][nx] !=-2 && !visited[ny][nx]) {
hedgehog.offer(new Node(nx,ny, poll.count+1));
visited[ny][nx]=true;
}
}
}
}
System.out.println( "KAKTUS");
}
private static boolean checkRange(int nx, int ny) {
return ny >= 0 && ny < R && nx >= 0 && nx < C;
}
static class Node {
private int x;
private int y;
private int count;
public Node(int x, int y, int count) {
this.x = x;
this.y = y;
this.count = count;
}
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
}
😎코드가 길지만 사실 내용은 별거 없다.
1.먼저 첫번째for
문을 통해 물의 위치,고슴도치 위치등을 입력받는다. 이 때 시작위치를 미리queue
에 넣고 물의 위치도 다른queue
에 넣는다.2.다음
while
문을 도는데 첫번째for
문에서는 물의 위치를 4방향으로 늘린다.3.그 다음 고슴도치를 이동시키는데 문제의 내용을 보면 다음 턴에 물과 고슴도치가 만난다면 그 자리는 고슴도치가 갈 수 없는 위치로 지정하라고 하였기에 물을 먼저 이동시킨 것이다.
4.이 과정을 돌면서 도착지를 만나면 값을
return
을 하고 만약while
문을 다 돌았는데도 도착지에 가지 못하였다면 "KAKTUS"를 반환한다.
개인적으로 data class를 선언하고 푸는 것을 좋아해서 class를 선언하였지만 이것이 불편하다면 배열을 선언해서 풀어도 된다.
출처 : 백준 - 탈출