|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +class Solution |
| 6 | +{ |
| 7 | + public static void main(String[] args) throws Exception{ |
| 8 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 9 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 10 | + |
| 11 | + int N = Integer.parseInt(st.nextToken()); |
| 12 | + ArrayList<Position> target = new ArrayList<>(); |
| 13 | + long[][] dp = new long[N+1][5]; // 0:정위치 1:북 2:동 3:남 4:서 |
| 14 | + int[][] dir = new int[][] {{0,0}, {-1,0}, {0,1}, {1,0}, {0,-1}}; |
| 15 | + long answer = Long.MAX_VALUE; |
| 16 | + |
| 17 | + for (int i = 0; i< N+1; i++) { |
| 18 | + st = new StringTokenizer(br.readLine()); |
| 19 | + target.add(new Position(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()))); |
| 20 | + Arrays.fill(dp[i], Long.MAX_VALUE); |
| 21 | + } |
| 22 | + for (int i = 0 ; i < 5; i++) { |
| 23 | + if (i == 0) { |
| 24 | + dp[0][0] = 0; |
| 25 | + } else { |
| 26 | + dp[0][i] = 1; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + for (int i = 1; i < N+1; i++) { |
| 31 | + for (int j = 0; j < 5; j++) { |
| 32 | + //이전꺼 위치 |
| 33 | + int y = target.get(i-1).y + dir[j][0]; |
| 34 | + int x = target.get(i-1).x + dir[j][1]; |
| 35 | + for (int z = 0; z < 5; z++) { |
| 36 | + //이번꺼 위치 |
| 37 | + int ty = target.get(i).y + dir[z][0]; |
| 38 | + int tx = target.get(i).x + dir[z][1]; |
| 39 | + //목표 위치의 상하좌우 |
| 40 | + dp[i][z] = Math.min(dp[i][z], Math.abs(y-ty)+Math.abs(x-tx)+dp[i-1][j]); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + for (int i = 0; i < 5; i++) { |
| 45 | + answer = Math.min(answer, dp[N][i]); |
| 46 | + } |
| 47 | + System.out.println(answer); |
| 48 | + } |
| 49 | + |
| 50 | + static class Position { |
| 51 | + int y; |
| 52 | + int x; |
| 53 | + public Position(int y, int x) { |
| 54 | + this.y = y; |
| 55 | + this.x = x; |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +``` |
0 commit comments