728x90
문제
https://www.acmicpc.net/problem/4485
4485번: 녹색 옷 입은 애가 젤다지?
젤다의 전설 게임에서 화폐의 단위는 루피(rupee)다. 그런데 간혹 '도둑루피'라 불리는 검정색 루피도 존재하는데, 이걸 획득하면 오히려 소지한 루피가 감소하게 된다! 젤다의 전설 시리즈의 주
www.acmicpc.net
해설
입구에서 출구까지의 모든 경로의 가장 낮은 숫자의 합을 구하는 문제입니다.
각 위치별 경로의 최소합을 얻기위해 dp 지도를 만듭니다.
dp[i][j] 는 (i,j)위치까지 가는 경로의 최소합을 의미합니다.
BFS를 통해 4방탐색으로 다음 위치는 이전 위치 + 진입 숫자보다 작은 경우 갱신하며 새로 큐에 넣는 방식을 통해 dp에 항상 최소값을 갱신할 수 있도록 구현했습니다.
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main{
static class point implements Comparable<point>{
int r,c,w;
public point(int r, int c,int w) {
super();
this.r = r;
this.c = c;
this.w = w;
}
@Override
public int compareTo(point o) {
// TODO Auto-generated method stub
return this.w-o.w;
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int N = Integer.parseInt(br.readLine());
int tc=1;
while(N!=0) {
int map[][] = 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());
}
}
int dp[][] = new int [N][N];
for(int i=0;i<N;i++) {
Arrays.fill(dp[i], Integer.MAX_VALUE);
}
PriorityQueue<point> pq = new PriorityQueue<>();
pq.add(new point(0, 0,map[0][0]));
dp[0][0] = map[0][0];
int dr[] = {-1,0,1,0};
int dc[] = {0,1,0,-1};
while(!pq.isEmpty()) {
point current = pq.poll();
for(int i=0;i<4;i++) {
int newr = current.r+dr[i];
int newc = current.c+dc[i];
if(newr<0 || newc<0 || newr>=N || newc>=N) continue;
if(dp[newr][newc]>dp[current.r][current.c]+map[newr][newc]) {
dp[newr][newc] = dp[current.r][current.c]+map[newr][newc];
pq.add(new point(newr, newc, dp[newr][newc]));
}
}
}
System.out.println("Problem "+tc+": "+dp[N-1][N-1]);
N = Integer.parseInt(br.readLine());
tc++;
}
}
}
728x90
'[IT] 코딩테스트 > [문제 및 풀이] 백준' 카테고리의 다른 글
[백준] 1937 욕심쟁이 판다 / 자바(Java) (1) | 2023.11.30 |
---|---|
[백준] 6198 옥상 정원 꾸미기 / 자바(Java) (1) | 2023.11.29 |
[백준] 3109 빵집 / 자바(Java) (3) | 2023.11.27 |
[백준] 3190 뱀 / 자바(Java) (0) | 2023.11.24 |
[백준] 2589 보물섬 / 자바(Java) (1) | 2023.11.23 |