백준 - 4485번(녹색 옷 입은 애가 젤다지?)

최지홍·2022년 4월 2일
0

백준

목록 보기
115/145

문제 출처: https://www.acmicpc.net/problem/4485


문제

  • 젤다의 전설 게임에서 화폐의 단위는 루피(rupee)다. 그런데 간혹 '도둑루피'라 불리는 검정색 루피도 존재하는데, 이걸 획득하면 오히려 소지한 루피가 감소하게 된다!

  • 젤다의 전설 시리즈의 주인공, 링크는 지금 도둑루피만 가득한 N x N 크기의 동굴의 제일 왼쪽 위에 있다. [0][0]번 칸이기도 하다. 왜 이런 곳에 들어왔냐고 묻는다면 밖에서 사람들이 자꾸 "젤다의 전설에 나오는 녹색 애가 젤다지?"라고 물어봤기 때문이다. 링크가 녹색 옷을 입은 주인공이고 젤다는 그냥 잡혀있는 공주인데, 게임 타이틀에 젤다가 나와있다고 자꾸 사람들이 이렇게 착각하니까 정신병에 걸릴 위기에 놓인 것이다.

  • 하여튼 젤다...아니 링크는 이 동굴의 반대편 출구, 제일 오른쪽 아래 칸인 [N-1][N-1]까지 이동해야 한다. 동굴의 각 칸마다 도둑루피가 있는데, 이 칸을 지나면 해당 도둑루피의 크기만큼 소지금을 잃게 된다. 링크는 잃는 금액을 최소로 하여 동굴 건너편까지 이동해야 하며, 한 번에 상하좌우 인접한 곳으로 1칸씩 이동할 수 있다.

  • 링크가 잃을 수밖에 없는 최소 금액은 얼마일까?


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class Main {

    private static class Node implements Comparable<Node> {

        int weight;
        int row;
        int col;

        public Node(int weight, int row, int col) {
            this.weight = weight;
            this.row = row;
            this.col = col;
        }

        @Override
        public int compareTo(Node o) {
            return this.weight - o.weight;
        }
    }

    public static void main(String[] args) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        int[][] directions = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 }, };

        int idx = 0;
        int N = 0;

        while ((N = Integer.parseInt(reader.readLine())) != 0) {
            int[][] matrix = new int[N][N];
            int[][] costs = new int[N][N];
            boolean[][] visited = new boolean[N][N];

            for (int i = 0; i < N; i++) {
                StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
                for (int j = 0; j < N; j++) {
                    matrix[i][j] = Integer.parseInt(tokenizer.nextToken());
                    costs[i][j] = Integer.MAX_VALUE;
                }
            }

            costs[0][0] = matrix[0][0];

            PriorityQueue<Node> pq = new PriorityQueue<>();
            pq.offer(new Node(matrix[0][0], 0, 0));

            while (!pq.isEmpty()) {
                Node node = pq.poll();

                if (visited[node.row][node.col]) continue;
                if (node.row == N - 1 && node.col == N - 1) break;

                visited[node.row][node.col] = true;

                for (int i = 0; i < 4; i++) {
                    int dy = node.row + directions[i][0];
                    int dx = node.col + directions[i][1];

                    if (dy >= 0 && dy < N && dx >= 0 && dx < N) {
                        if (costs[dy][dx] > costs[node.row][node.col] + matrix[dy][dx]) {
                            costs[dy][dx] = costs[node.row][node.col] + matrix[dy][dx];
                            pq.offer(new Node(costs[dy][dx], dy, dx));
                        }
                    }
                }
            }

            sb.append("Problem ").append(++idx).append(": ");
            sb.append(costs[N - 1][N - 1]).append("\n");
        }

        System.out.println(sb);
    }

}

  • 다익스트라 알고리즘을 응용하여 문제를 해결하였다.
profile
백엔드 개발자가 되자!

0개의 댓글