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

이형욱·2025년 4월 22일
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.StringTokenizer;

public class Main {
    // 동, 서, 남, 북
    static int[] dy = {0, 0, 1, -1};
    static int[] dx = {1, -1, 0, 0};
    static int N;
    static int[][] map, dp;
    static final int INF = Integer.MAX_VALUE;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int cnt = 1;
        while(true){
            N = Integer.parseInt(br.readLine());
            if(N==0)break;
            map = new int[N][N];
            for(int i=0; i<N; i++){
                StringTokenizer st = new StringTokenizer(br.readLine());
                for(int j=0;j<N; j++){
                    map[i][j] = Integer.parseInt(st.nextToken());
                }
            }

            // 완탐 수행.
            dp = new int[N][N];
            for(int i=0; i<N; i++){
                Arrays.fill(dp[i], INF);
            }
            bfs(0,0);

            System.out.println("Problem "+cnt+": "+dp[N-1][N-1]);
            cnt++;
        }
    }

    static void bfs(int startY, int startX){
        dp[startY][startX] = map[startY][startX];

        Deque<int[]> queue = new ArrayDeque<>();
        queue.offer(new int[]{startY, startX});

        while(!queue.isEmpty()){
            int[] items = queue.poll();
            int y = items[0];
            int x = items[1];

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

                if(ny<0 || ny >=N || nx < 0 || nx >=N) continue;

                if(dp[y][x]+map[ny][nx] < dp[ny][nx]){
                    dp[ny][nx]=dp[y][x]+map[ny][nx];
                    queue.offer(new int[]{ny, nx});
                }
            }
        }
    }
}
profile
바나나는 하드디스크보다 따듯하다.

0개의 댓글