자료구조&알고리즘/백준

4485번: 녹색 옷 입은 애가 젤다지? [JAVA]

yong_ღ'ᴗ'ღ 2023. 10. 29. 03:18

https://www.acmicpc.net/problem/4485

 

4485번: 녹색 옷 입은 애가 젤다지?

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

www.acmicpc.net

 

접근 방식) 다익스트라

 

1. int[][] map을 생성해서 각 칸의 도둑루피를 저장해준다.

    잃게 될 최소 루피를 저장할 int[][] rupee 배열을 Integer.MAX_VALUE로 초기화해준다.

 

2. map[0][0] 을 시작점으로 BFS를 시작해서 

    각 지점마다 상하좌우로 돌면서 최소 루피를 구해 rupee[][] 값을 갱신한다.

 

3. BFS에서는 queue대신, 잃게되는 루피가 적은 순으로 먼저 꺼내서 살펴보기 위해 우선순위 큐를 사용한다.

   ⭐우선순위 큐의 정렬 기준을 정의해줘야 한다. (→ 잃는 루피 오름차순 정렬)

    초깃값을 세팅해주고, 우선순위큐가 빌 때까지 반복한다.

    상하좌우 4방향으로 돌면서 map[][] 을 벗어나지 않고, 이미 방문했던 곳이 아니라면(→ rupee[][]가 Integer.MAX_VALUE인지 확인)

    →  지금 계산한 잃는 루피가 현재 rupee[x][y] 보다 작다면 update해준다.

    → 그리고 우선순위 큐에 x, y를 추가해준다.

 

4. 결과값 출력: 모든 과정을 끝내면 rupee[N-1][N-1]에는 잃게 될 최소 루피가 저장되어 있다.

 

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

public class B_4485 {
    static int N;
    static int[][] map;     // 도둑루피 값 배열
    static int[][] rupee;   // 잃게 되는 최소 루피 계산하기 위한 배열
    static int[] dx = {0, 0, -1, 1};
    static int[] dy = {1, -1, 0, 0};
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        StringTokenizer st;
        int num = 1;
        while (true) {
            N = Integer.parseInt(br.readLine());    // 동굴 가로,세로 크기
            if (N == 0) break;

            map = new int[N][N];
            rupee = new int[N][N];

            for (int i = 0; i < N; i++) {
                st = new StringTokenizer(br.readLine());
                for (int j = 0; j < N; j++) {
                    map[i][j] = Integer.parseInt(st.nextToken());
                    rupee[i][j] = Integer.MAX_VALUE;    // rupee[][] 초기화
                }
            }

            bfs(0, 0);
            sb.append("Problem " + num++ + ": ").append(rupee[N - 1][N - 1]).append('\n');
        }
        System.out.print(sb);
    }

    static void bfs(int i, int j) {
        PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> {
            // 잃는 금액 오름차순 정렬 정의
            return rupee[o1[0]][o1[1]] - rupee[o2[0]][o2[1]];
        });
        pq.add(new int[]{i, j});
        rupee[i][j] = map[i][j];

        while (!pq.isEmpty()) {
            int[] now = pq.poll();
            for (int k = 0; k < 4; k++) {
                int x = now[0] + dx[k];
                int y = now[1] + dy[k];

                if (x < 0 || y < 0 || x >= N || y >= N) continue;
                if (rupee[x][y] == Integer.MAX_VALUE) {
                    rupee[x][y] = Math.min(rupee[x][y], rupee[now[0]][now[1]] + map[x][y]);
                    pq.add(new int[]{x, y});
                }
            }
        }
    }
}