문제 풀이 및 개발 공간

[백준] 4485번 녹색 옷 입은 애가 젤다지? (gold 4 본문

백준공부/java

[백준] 4485번 녹색 옷 입은 애가 젤다지? (gold 4

gomduri43 2024. 4. 5. 14:27

import java.io.*;
import java.util.*;

class Point{
    int x;
    int y;
    int v;
    public Point(int x, int y, int v){
        this.x=x;
        this.y=y;
        this.v=v;
    }
}
public class Main{
    static int[] numx={-1,1,0,0};
    static int[] numy={0,0,-1,1};
    public static void main(String[] args) throws IOException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
        StringTokenizer st;
        int t=0;
        while(true){
            int n=Integer.valueOf(br.readLine());
            if(n==0){
                break;
            }
            t++;

            int[][] map=new int[n+1][n+1];
            for(int i=1; i<=n; i++){
                st=new StringTokenizer(br.readLine());
                for(int j=1; j<=n; j++){
                    map[i][j]=Integer.valueOf(st.nextToken());
                }
            }

            PriorityQueue<Point> que=new PriorityQueue<>(new Comparator<Point>(){
                public int compare(Point o1, Point o2){
                    return o1.v-o2.v;
                }
            });

            boolean[][] visit=new boolean[n+1][n+1];

            que.offer(new Point(1,1,map[1][1]));
            visit[1][1]=true;
            while(!que.isEmpty()){
                Point temp=que.poll();
                if(temp.y==n && temp.x==n){
                    bw.write("Problem "+t+": "+temp.v+"\n");
                    break;
                }

                for(int i=0; i<4; i++){
                    int tx=temp.x+numx[i];
                    int ty=temp.y+numy[i];

                    if(tx<1 || tx>n || ty<1 || ty>n || visit[ty][tx]){
                        continue;
                    }
                    visit[ty][tx]=true;
                    que.offer(new Point(tx, ty , temp.v+map[ty][tx]));
                }
            }
        }
        bw.flush();
    }
}

//pq로 순서만 잘 정해주면 해결되는 간단한 bfs문제ㅁ

'백준공부 > java' 카테고리의 다른 글

[백준] 1461번 도서관 (gold 4  (0) 2024.04.07
[백준] 1132번 합 (gold 3  (0) 2024.04.06
[백준] 16234번 인구이동 (gold 4  (0) 2024.04.05
[백준] 16236번 아기상어 (gold 3  (0) 2024.04.04
[백준] 3190번 뱀 (gold 4  (0) 2024.04.03