Notice
Recent Posts
Recent Comments
Link
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

forDevLife

[백준] 4485 - 녹색 옷 입은 애가 젤다지? 본문

알고리즘

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

JH_Lucid 2021. 7. 10. 21:25

 

Priority Queue를 활용한 BFS => 다익스트라 방식으로 풀었다.

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

class Point {
    int x;
    int y;
    int val;

    public Point(int x, int y, int val) {
        this.x = x;
        this.y = y;
        this.val = val;
    }
}

public class Solution {

    static int[] dx = {-1, 0, 1, 0};
    static int[] dy = {0, 1, 0, -1};

    static int solution(int N, int[][] arr) {
        int answer = 0;
        PriorityQueue<Point> pq = new PriorityQueue<>(new Comparator<Point>() {
            @Override
            public int compare(Point o1, Point o2) {
                return o1.val - o2.val;
            }
        });

        boolean[][] chk = new boolean[N][N];
        pq.offer(new Point(0, 0, arr[0][0]));
        chk[0][0] = true;

        while(!pq.isEmpty()) {
            Point tmp = pq.poll();

            for(int i=0; i<4; i++) {
                int nx = dx[i] + tmp.x;
                int ny = dy[i] + tmp.y;

                if(nx == N-1 && ny == N-1) {
                    answer = tmp.val + arr[nx][ny];
                    return answer;
                }

                if(nx >=0 && nx <N && ny>=0 && ny < N && !chk[nx][ny]) {
                    chk[nx][ny] = true;
                    pq.offer(new Point(nx, ny, tmp.val + arr[nx][ny]));
                }
            }
        }
        return answer;
    }

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

        int N;
        int count = 1;
        int sol;

        while(true) {
            st = new StringTokenizer(br.readLine(), " ");
            N = Integer.parseInt(st.nextToken());
            if(N == 0) {
                break;
            }
            int[][] arr = new int[N][N];
            for(int i=0; i<N; i++) {
                st = new StringTokenizer(br.readLine(), " ");
                for(int j=0; j<N; j++) {
                    arr[i][j] = Integer.parseInt(st.nextToken());
                }
            }

            sol = solution(N, arr);
            sb.append("Problem ").append(count).append(": ").append(sol).append("\n");
            count ++;
        }
        System.out.println(sb.toString());
    }
}

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

[백준] 2667 - 단지 번호 붙이기  (0) 2021.07.15
[백준] 2178 - 미로탐색  (0) 2021.07.15
[프로그래머스] 문자열 압축  (0) 2021.07.09
[프로그래머스] 튜플  (0) 2021.07.08
[프로그래머스] 기능개발  (0) 2021.07.08
Comments