August 04, 2022
백준 문제 링크 : https://www.acmicpc.net/problem/4485
package backjoon.P4485;
import java.io.*;
import java.util.*;
public class Main {
static class Node {
public int r, c, val;
public Node(int r, int c, int val) {
this.r = r;
this.c = c;
this.val = val;
}
}
static int[] dy = {-1, 0, 1, 0};
static int[] dx = {0, 1, 0, -1};
static int[][] dp;
static int[][] map;
public static int dijkstra(int N) {
PriorityQueue<Node> q = new PriorityQueue<>((n1, n2) -> n1.val - n2.val);
dp[0][0] = map[0][0];
q.add(new Node(0, 0, map[0][0]));
while (!q.isEmpty()) {
Node cur = q.poll();
for (int i = 0; i < 4; i++) {
int rr = cur.r + dy[i];
int cc = cur.c + dx[i];
if (rr < 0 || rr >= N || cc < 0 || cc >= N)
continue;
int nextVal = cur.val + map[rr][cc];
// 이거 한줄 떄매 계속 문제남 .... <= 로 처리를 해주면 되는데
// 나는 < 로 처리함 -> 중복되는 것을 구했기 때문에 메모리 초과
if (dp[rr][cc] <= nextVal)
continue;
dp[rr][cc] = nextVal;
q.add(new Node(rr, cc, nextVal));
}
}
return dp[N - 1][N - 1];
}
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("src/backjoon/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
StringBuilder sb = new StringBuilder("");
int p = 0;
while (true) {
int N = Integer.parseInt(br.readLine());
p++;
if (N == 0)
break;
dp = new int[N][N];
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());
dp[i][j] = Integer.MAX_VALUE;
}
}
System.out.println("Problem " + p + ": " + dijkstra(N));
}
bw.flush();
}
}