|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int N,T; |
| 7 | + static int[][] farm; |
| 8 | + static long[][][] dist; |
| 9 | + static int[] di = {0,0,-1,1}; |
| 10 | + static int[] dj = {-1,1,0,0}; |
| 11 | + static long ans; |
| 12 | + |
| 13 | + public static void main(String[] args) throws IOException { |
| 14 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 15 | + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 16 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 17 | + N = Integer.parseInt(st.nextToken()); |
| 18 | + T = Integer.parseInt(st.nextToken()); |
| 19 | + farm = new int[N][N]; |
| 20 | + |
| 21 | + for (int i = 0; i < N; i++) { |
| 22 | + st = new StringTokenizer(br.readLine()); |
| 23 | + for (int j = 0; j < N; j++) { |
| 24 | + farm[i][j] = Integer.parseInt(st.nextToken()); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + dijkstra(); |
| 29 | + bw.write(ans+""); |
| 30 | + bw.close(); |
| 31 | + } |
| 32 | + |
| 33 | + static void dijkstra(){ |
| 34 | + dist = new long[N][N][3]; |
| 35 | + for (int i = 0; i < N; i++) { |
| 36 | + for (int j = 0; j < N; j++) { |
| 37 | + Arrays.fill(dist[i][j],Long.MAX_VALUE); |
| 38 | + } |
| 39 | + } |
| 40 | + dist[0][0][0] = 0; |
| 41 | + PriorityQueue<long[]> pq = new PriorityQueue<>((a,b) -> Long.compare(a[2],b[2])); |
| 42 | + pq.offer(new long[]{0,0,0,0}); // a,b,c,d : [a][b]까지 가는데 c만큼 걸리고 길 건넌 횟수는 d이다. |
| 43 | + |
| 44 | + while(!pq.isEmpty()){ |
| 45 | + long[] cur = pq.poll(); |
| 46 | + |
| 47 | + if(dist[(int)cur[0]][(int)cur[1]][(int)cur[3]] < cur[2]) continue; |
| 48 | + |
| 49 | + for (int k = 0; k < 4; k++) { |
| 50 | + int newi = (int)(cur[0] + di[k]); |
| 51 | + int newj = (int)(cur[1] + dj[k]); |
| 52 | + if(check(newi,newj)){ |
| 53 | + long newDist = cur[2] + T; |
| 54 | + int newCross = (int)(cur[3]+1) % 3; |
| 55 | + if(newCross == 0){ |
| 56 | + newDist += farm[newi][newj]; |
| 57 | + } |
| 58 | + if(newDist < dist[newi][newj][newCross]){ |
| 59 | + dist[newi][newj][newCross] = newDist; |
| 60 | + pq.offer(new long[]{newi,newj,newDist,newCross}); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + ans = Math.min(dist[N-1][N-1][0],Math.min(dist[N-1][N-1][1], dist[N-1][N-1][2])); |
| 66 | + } |
| 67 | + static boolean check(long a, long b){ |
| 68 | + if(a<0 || a>=N || b<0 || b>=N) return false; |
| 69 | + return true; |
| 70 | + } |
| 71 | +} |
| 72 | +``` |
0 commit comments