4485번: 녹색 옷 입은 애가 젤다지?
젤다의 전설 게임에서 화폐의 단위는 루피(rupee)다. 그런데 간혹 '도둑루피'라 불리는 검정색 루피도 존재하는데, 이걸 획득하면 오히려 소지한 루피가 감소하게 된다! 젤다의 전설 시리즈의 주
www.acmicpc.net
아이디어💡
처음에는 DFS(백트래킹)을 이용하는 방법을 생각했다. 하지만 시간초과가 나서 다익스트라를 활용하는 것으로 변경하니 성공했다.
DFS (백트래킹) → 시간초과
결론 : 다익스트라
시간복잡도⌛
우선 순위 큐 삽입 / 삭제 연산 : O(log N)
-> 우선 순위에 모든 노드를 우선순위에 삽입 / 삭제 : O(N^2 * log(N))
전체 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int testCase = 1;
int[][] arr;
int N;
int answer;
final int INF = 225000; // 대충 150x150x10
int[] dx = {0,0,1,-1};
int[] dy = {1,-1,0,0};
while(true){
N = Integer.parseInt(br.readLine());
if(N == 0) break;
answer = Integer.MAX_VALUE;
arr = new int[N][N];
for(int i=0; i<N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j=0; j<N; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
int[][] distances = new int[N][N];
for(int i=0; i<N; i++) {
Arrays.fill(distances[i], INF);
}
distances[0][0] = arr[0][0];
PriorityQueue<Route> pq = new PriorityQueue<>();
pq.offer(new Route(0, 0, arr[0][0]));
while(!pq.isEmpty()) {
Route route = pq.poll();
if(route.dist > distances[route.x][route.y]) continue; // 이미 완성된 친구는 패스
for(int i=0; i<dx.length; i++) {
int cx = route.x + dx[i];
int cy = route.y + dy[i];
if(cx < 0 || cx >= N || cy < 0 || cy >= N) continue; // 범위체크
int cost = route.dist + arr[cx][cy];
if(cost < distances[cx][cy]) {
distances[cx][cy] = cost;
pq.offer(new Route(cx, cy, cost));
}
}
}
bw.write("Problem " + testCase++ + ": " + distances[N-1][N-1] + "\n");
bw.flush();
}
bw.close();
}
static class Route implements Comparable<Route> {
int x, y;
int dist;
public Route(int x, int y, int dist) {
this.x = x;
this.y = y;
this.dist = dist;
}
@Override
public int compareTo(Route o) {
return this.dist - o.dist;
}
}
}
'알고리즘' 카테고리의 다른 글
[백준] 20056. 마법사 상어와 파이어볼 (Java) (0) | 2024.04.21 |
---|---|
[백준] 21610. 마법사 상어와 비바라기 (Java) (0) | 2024.04.21 |
[백준] 7579. 앱(Java) (0) | 2024.04.21 |
[백준] 1463. 1로 만들기(Java) (0) | 2024.04.21 |
[백준] 2747. 피보나치 수(Java) (1) | 2024.04.21 |