●문제 출처
●정리(요약)
알고스팟 운영진이 모두 미로에 갇혔다. 미로는 NM 크기이며, 총 11크기의 방으로 이루어져 있다. 미로는 빈 방 또는 벽으로 이루어져 있고, 빈 방은 자유롭게 다닐 수 있지만, 벽은 부수지 않으면 이동할 수 없다.
알고스팟 운영진은 여러명이지만, 항상 모두 같은 방에 있어야 한다. 즉, 여러 명이 다른 방에 있을 수는 없다. 어떤 방에서 이동할 수 있는 방은 상하좌우로 인접한 빈 방이다. 즉, 현재 운영진이 (x, y)에 있을 때, 이동할 수 있는 방은 (x+1, y), (x, y+1), (x-1, y), (x, y-1) 이다. 단, 미로의 밖으로 이동 할 수는 없다.
벽은 평소에는 이동할 수 없지만, 알고스팟의 무기 AOJ를 이용해 벽을 부수어 버릴 수 있다. 벽을 부수면, 빈 방과 동일한 방으로 변한다.
만약 이 문제가 알고스팟에 있다면, 운영진들은 궁극의 무기 sudo를 이용해 벽을 한 번에 다 없애버릴 수 있지만, 안타깝게도 이 문제는 Baekjoon Online Judge에 수록되어 있기 때문에, sudo를 사용할 수 없다.
현재 (1, 1)에 있는 알고스팟 운영진이 (N, M)으로 이동하려면 벽을 최소 몇 개 부수어야 하는지 구하는 프로그램을 작성하시오.
●코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
static int M, N;
static int[][] arr;
static int[] dx = {1, 0, -1, 0};
static int[] dy = {0, 1, 0, -1};
static class pos implements Comparable<pos> {
int x;
int y;
int cnt;
public pos(int x, int y, int cnt) {
this.x = x;
this.y = y;
this.cnt = cnt;
}
@Override
public int compareTo(pos o) {
return this.cnt - o.cnt;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
M = Integer.parseInt(st.nextToken());
N = Integer.parseInt(st.nextToken());
arr = new int[N][M];
for (int i = 0; i < N; i++) {
String[] str = br.readLine().split("");
int idx = 0;
for (String num : str) {
arr[i][idx] = Integer.parseInt(num);
idx++;
}
}
System.out.println(bfs(new pos(0, 0, 0)));
}
public static int bfs(pos start) {
PriorityQueue<pos> pq = new PriorityQueue<>();
int[][] dist = new int[N][M];
for (int i = 0; i < N; i++) {
Arrays.fill(dist[i], Integer.MAX_VALUE);
}
pq.add(start);
dist[start.y][start.x] = 0;
while (!pq.isEmpty()) {
pos nowPos = pq.poll();
if (nowPos.x == M - 1 && nowPos.y == N - 1) {
return nowPos.cnt;
}
if (dist[nowPos.y][nowPos.x] < nowPos.cnt) continue;
for (int i = 0; i < 4; i++) {
int nxtX = dx[i] + nowPos.x;
int nxtY = dy[i] + nowPos.y;
if (nxtX < 0 || nxtY < 0 || nxtX >= M || nxtY >= N) continue;
int nextCnt = nowPos.cnt + arr[nxtY][nxtX];
if (dist[nxtY][nxtX] > nextCnt) {
dist[nxtY][nxtX] = nextCnt;
pq.add(new pos(nxtX, nxtY, nextCnt));
}
}
}
return 0;
}
}
●느낀 점
