알고리즘

[4485] 녹색 옷 입은 애가 젤다지? - Java

주다애 2024. 2. 5. 23:10

백준 녹색 옷 입은 애가 젤다지? (골드 IV )

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

// 녹색 옷 입은 애가 젤다지?(골드 4)
// 다익스트라
public class Main {
    static int[][] zelda;
    static boolean[][] visited;
    static int N;
    static int cnt = 0;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        List<Integer> res = new ArrayList<>();
        // N = 0일 때까지 반복
        while(true) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            N = Integer.parseInt(st.nextToken());
            if(N == 0) break;
            zelda = new int[N][N];
            visited = new boolean[N][N];
            for(int i = 0; i < N; i++) {
                st = new StringTokenizer(br.readLine(), " ");
                for(int j = 0; j < N; j++) {
                    zelda[i][j] = Integer.parseInt(st.nextToken());
                }
            }
            res.add(bfs());
        }
        for(int i = 1; i <= res.size(); i++) {
            System.out.println("Problem " + i + ": " + res.get(i - 1));
        }
    }

    private static int bfs() {
        PriorityQueue<int[]> q = new PriorityQueue<>(Comparator.comparingInt(a -> a[a.length - 1]));
        q.offer(new int[]{0, 0, zelda[0][0]});
        visited[0][0] = true;
        int[][] dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        // 거리 누적 합 저장 배열 dist
        int[][] dist = new int[N][N];
        for(int[] row : dist) {
            Arrays.fill(row, Integer.MAX_VALUE);
        }
        dist[0][0] = 0;

        while(!q.isEmpty()) {
            int[] target = q.poll();
            int cx = target[0];
            int cy = target[1];
            int rupee = target[2];
            if(cx == N - 1 && cy == N - 1) {
                return rupee + zelda[0][0];
            }
            for(int[] d : dir) {
                int nx = cx + d[0];
                int ny = cy + d[1];
                if(canMove(nx, ny)) {
                    if(dist[nx][ny] > dist[cx][cy] + zelda[nx][ny]) {
                        dist[nx][ny] = dist[cx][cy] + zelda[nx][ny];
                        q.offer(new int[]{nx, ny, dist[nx][ny]});
                    }
                }
            }
        }
        return -1;
    }

    private static boolean canMove(int x, int y) {
        if(x < 0 || x >= N || y < 0 || y >= N) return false;
        return true;
    }
}

 

다익스트라 문제

우선순위 큐 사용해서 rupee 값으로 오름차순

PriorityQueue<int[]> q = new PriorityQueue<>(Comparator.comparingInt(a -> a[a.length - 1]));

 

새로운 배열 dist(거리 누적 합 저장) + MAX값으로 초기화

int[][] dist = new int[N][N];
for(int[] row : dist) {
    Arrays.fill(row, Integer.MAX_VALUE);
}
dist[0][0] = 0;

'알고리즘' 카테고리의 다른 글

0-1 BFS  (1) 2024.04.04
[15651] N과 M(3) - Java  (0) 2023.12.22
[15650] N과 M(2) - Java  (0) 2023.12.22